简体   繁体   中英

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. As you can see res.status(400).json({"error": "Invalid input"}) is repeating a lot, in different files and modules actually.

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() .

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();
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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