Accessing res.locals after app.router

最后都变了- 提交于 2019-12-12 15:19:32

问题


I am creating the middleware to be called after app.router and I need to access the data that was stored in res.locals object by the route middleware and route handler.

//...
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
}

The problem is that all properties of res.locals become empty after app.router.

I tried to find the place where express or connect cleans res.locals to somehow patch it but so far I can't find it.

The only solution I see at the moment is to abandon the idea of putting this logic in a separate middleware and put it in route-specific middleware, where res.locals is available, but it will make the system much more interconnected. Also I have many routes where route middleware does not call next (when res.redirect is called), so I will have to do many changes to make it work. I'd very much like to avoid it and put this logic in a separate middleware, but I need to access the data that was stored in res.locals.

Any help really appreciated.


回答1:


You can possibly bind it before, but have it act after. The logger middleware is an example of this.

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()`
});

Requesting / results in:

GET / 200 3 - 6 ms
there is data
GET /favicon.ico 404 - - 1 ms
data is removed


来源:https://stackoverflow.com/questions/15792665/accessing-res-locals-after-app-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!