扩展expressjs资源
目前我正在尝试添加一个错误&通知function到我的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'); });
但是,上面的示例不起作用。 有没有办法完成我想要做的?
添加notice
方法到res
后,您需要调用next
。
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);