extend expressjs res property

时间:2012-09-01 17:43:31

标签: javascript node.js express

当前我正在尝试添加错误&通知我expressjs应用的功能。我想通过调用

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

通知功能将附加到我的应用程序中的所有res对象,使我能够按如下方式使用它:

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

但是,上面的示例不起作用。有没有办法完成我想要做的事情?

1 个答案:

答案 0 :(得分:9)

next方法添加到notice后,您需要致电res

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

您需要在路由定义之前添加此中间件。

更新:

您需要在路由器之前添加中间件。

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