Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extend expressjs res property

Currenty I am trying to add an error & notice function to my expressjs app. I thought that by calling

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

the notice function would be attached to all res objects present in my application, enabling me to use it as follows:

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

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

like image 859
R.G. Avatar asked Sep 01 '12 17:09

R.G.


1 Answers

You need to call next after adding notice method to res, and you need to add the middleware before routes definition.

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);
like image 76
Vadim Baryshev Avatar answered Oct 19 '22 10:10

Vadim Baryshev