Extend expressjs res property

I am currently trying to add an error and notification function to my expressjs application . I thought calling

app.use(function (req, res, next) {
  res.notice = function (msg) {
    res.send([Notice] ' + msg);
  }
});

the notification function will be attached to all res objects present in my application, which will allow me to use it as follows:

app.get('something', function (req, res) {
  res.notice('Test');
});

However, the above example does not work. Is there a way to accomplish what I'm trying to do?

+5
source share
1 answer

You need to call nextafter adding method noticeto res.

app.use(function (req, res, next) {
  res.notice = function (msg) {
     res.send('[Notice] ' + msg);
  }
  next();
});

And you need to add this middleware before determining the routes.

UPDATE:

You need to add your middleware in front of the router.

var express = require('express');
var app = express();

app.use(function (req, res, next) {
    res.notice = function (msg) {
        res.send('[Notice] ' + msg);
    };
    next();
});

app.use(app.router);
app.get('/', function (req, res) {
    res.notice('Test');
});

app.listen(3000);
+8
source

All Articles