如何在Node.JS中为响应对象添加自定义函数 [英] How to add custom function to response object in Node.JS

查看:93
本文介绍了如何在Node.JS中为响应对象添加自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的API应用程序中,我对不同部分的错误有一个固定的响应。正如你可以看到 res.status(400).json({error:Invalid input})在不同的文件和模块中重复了很多。

In my API-application I have a fixed response for errors in different parts. As you can see res.status(400).json({"error": "Invalid input"}) is repeating a lot, in different files and modules actually.

我可以创建模块功能 invalidInput(res),这将消除重复,但我真的希望作为 res 对象的全局部分,如 res.invalidInput()

I could create module-function invalidInput(res), which will eliminate duplication, but I really want this to be global part of res object, like res.invalidInput().

我如何使用JS / Node.JS?

How could I make it in JS/Node.JS?

router.get("/users", function(req, res) {
    // ...
    if (error) {
        return res.status(400).json({"error": "Invalid input"});
    }
});

router.get("/items", function(req, res) {
    // ...
    if (error) {
        return res.status(400).json({"error": "Invalid input"});
    }
});

// etc


推荐答案

您可以使用自己的自定义中间件。将其添加到路由处理器上方的某个地方:

You can use your own custom middleware. Add this somewhere above your route handler:

router.use(function(req, res, next) {
    res.invalidInput = function() {
        return res.status(400).json({"error": "Invalid input"});
    };
    next();
});

然后你可以做 res.invalidInput()在您的路线处理程序。

and then you can do res.invalidInput() in your route handlers.

这篇关于如何在Node.JS中为响应对象添加自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆