在app.router之后访问res.locals

esp*_*esp 3 middleware connect node.js express

我正在创建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
}
Run Code Online (Sandbox Code Playgroud)

问题是res.locals的所有属性在app.router之后变为空.

我试图找到表达或连接的地方清理res.locals以某种方式修补它但到目前为止我找不到它.

我目前看到的唯一解决方案是放弃将这个逻辑放在一个单独的中间件中并将其放在特定于路由的中间件中的想法,其中res.locals可用,但它将使系统更加互连.此外,我有许多路由中间件不会调用下一个路由(当调用res.redirect时),因此我将不得不进行许多更改以使其工作.我非常想避免它并将此逻辑放在一个单独的中间件中,但我需要访问存储在res.locals中的数据.

任何帮助真的很感激.

Jon*_*ski 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()`
});
Run Code Online (Sandbox Code Playgroud)

请求/结果:

GET / 200 3 - 6 ms
there is data
GET /favicon.ico 404 - - 1 ms
data is removed
Run Code Online (Sandbox Code Playgroud)