简体   繁体   English

如何在Node.JS中向自定义函数添加响应对象

[英]How to add custom function to response object in Node.JS

In my API-application I have a fixed response for errors in different parts. 在我的API应用程序中,我对不同部分的错误有一个固定的响应。 As you can see res.status(400).json({"error": "Invalid input"}) is repeating a lot, in different files and modules actually. 正如您所看到的, res.status(400).json({"error": "Invalid input"})实际上在不同的文件和模块中重复了很多。

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() . 我可以创建模块函数invalidInput(res) ,这将消除重复,但我真的希望它是res对象的全局部分,如res.invalidInput()

How could I make it in JS/Node.JS? 我怎么能在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();
});

and then you can do res.invalidInput() in your route handlers. 然后你可以在路由处理程序中执行res.invalidInput()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM