how to extend express js res object in NodeJs how to extend express js res object in NodeJs express express

how to extend express js res object in NodeJs


As loadaverage pointed out, middleware is how you do it. For some more specificity:

app.use(function(req, res, next) {    res.jsonFail = function(users) {        return res.json({            success: false,            payload: users        })    };    res.jsonSuccess = function(users) {        return res.json({            success: true,            payload: users        });    };    next();});

and then this should work:

app.get("/my/route", function(req, res) {    return res.jsonSuccess(["you", "me"]);});


Sometimes I want to extend current method with new method.For example, log everything that I sent.

This what you can do:

app.use(function (req, res, next) {    var _send = res.send    res.send = function (data) {      console.log('log method on data', data)      // Call Original function      _send.apply(res, arguments)    })})


Sure, you can write some simple middleware, then app.use(yourmiddleware) just like usually.