extend expressjs res property

R.G*_*.G. 6 javascript node.js express

我正在尝试向我的expressjs应用添加错误和通知功能.我以为通过电话来考虑

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

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

app.get('something', function (req, res) {
  res.notice('Test');
});
Run Code Online (Sandbox Code Playgroud)

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

Vad*_*hev 10

next添加notice方法后需要调用res.

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

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

更新:

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

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);
Run Code Online (Sandbox Code Playgroud)