扩展expressjs res属性 [英] extend expressjs res property
本文介绍了扩展expressjs res属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当前,我正在尝试添加错误&通知我的 expressjs 应用程序的功能.我以为是通过致电
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);
}
});
notice函数将附加到应用程序中存在的所有res对象,使我可以按以下方式使用它:
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?
推荐答案
您需要在res
中添加notice
方法之后调用next
.
You need to call next
after adding notice
method to res
.
app.use(function (req, res, next) {
res.notice = function (msg) {
res.send('[Notice] ' + msg);
}
next();
});
并且您需要在路由定义之前添加此中间件.
And you need to add this middleware before routes definition.
更新:
您需要在路由器之前添加中间件.
You need to add your middleware before 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);
这篇关于扩展expressjs res属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文