调用app.router后如何访问res.locals?

问题描述 投票:0回答:1

我正在创建要在

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
}

问题是app.router之后res.locals的所有属性都变空了。

我试图找到express或connect清理的地方

res.locals
以某种方式修补它,但到目前为止我找不到它。

目前我看到的唯一解决方案是放弃将这个逻辑放在单独的中间件中的想法,并将其放在特定于路由的中间件中,其中

res.locals
可用,但它将使系统更加互连。另外,我有许多路线,其中路线中间件不会调用 next (当调用
res.redirect
时),所以我必须做很多更改才能使其工作。我非常想避免它并将此逻辑放在单独的中间件中,但我需要访问存储在
res.locals
中的数据。

非常感谢任何帮助。

node.js express middleware node.js-connect
1个回答
5
投票

您可以在之前绑定它,但让它在之后起作用。

logger
中间件就是一个例子。

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
© www.soinside.com 2019 - 2024. All rights reserved.