我正在创建要在 app.router 之后调用的中间件,我需要通过路由中间件和路由处理程序访问存储在 res.locals 对象中的数据。
//...
app.use(app.router);
app.use(myMiddleware);
//...
app.get('/', function(req, res) {
res.locals.data = 'some data';
});
function myMiddleware(req, res, next) {
if (res.locals.data)
console.log('there is data');
else
console.log('data is removed'); // that's what happens
}
问题是 res.locals 的所有属性在 app.router 之后都变空了。
我试图找到 express 或 connect 清理 res.locals 以某种方式修补它的地方,但到目前为止我找不到它。
我目前看到的唯一解决方案是放弃将此逻辑放在单独的中间件中的想法,并将其放在路由特定的中间件中,其中 res.locals 可用,但它会使系统更加互联。此外,我有许多路由中间件不会调用下一个(调用 res.redirect 时)的路由,因此我将不得不做很多更改才能使其工作。我非常想避免它并将此逻辑放在单独的中间件中,但我需要访问存储在 res.locals 中的数据。
非常感谢任何帮助。
最佳答案
您可以先绑定(bind)它,然后让它执行。 logger
middleware就是一个例子。
app.use(express.logger('tiny'));
app.use(myMiddleware);
app.use(app.router);
function myMiddleware(req, res, next) {
var end = res.end;
res.end = function (chunk, encoding) {
res.end = end;
res.end(chunk, encoding);
if (res.locals.data)
console.log('there is data');
else
console.log('data is removed');
};
next();
}
app.get('/', function (req, res) {
res.locals.data = 'some data';
res.send('foo'); // calls `res.end()`
});
请求 /
结果:
GET / 200 3 - 6 ms
there is data
GET /favicon.ico 404 - - 1 ms
data is removed
关于node.js - 在 app.router 之后访问 res.locals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15792665/