【发布时间】:2015-12-20 03:38:31
【问题描述】:
我很困惑这里发生了什么。如果用户当前没有,我正在尝试为用户设置 res.locals 默认个人资料图片。这是我的代码:
// Make user object available in templates.
app.use(function(req, res, next) {
res.locals.user = req.user;
if (req.user && req.user.profile) {
console.log('Request Picture: ', req.user.profile);
res.locals.user.profile.picture = req.user.profile.picture || defaults.imgs.profile;
console.log('Request Picture After Locals: ', req.user.profile);
}
next();
});
// Console Results
Request Picture: { picture: '',
website: '',
location: '',
gender: '',
name: 'picture' }
Request Picture After Locals: { picture: '/img/profile-placeholder.png',
website: '',
location: '',
gender: '',
name: 'picture' }
我希望能够编写 JADE 而不必处理类似这样的事情:img(src=user.profile.picture || defaults.profile.picture)。所以上面的代码在所有 JADE 视图中都可以正常工作。
但是,我需要在其他地方检查req.user.profile.picture 才能更改图片。
if (!req.user.profile.picture) {do stuff}
正如您在上面看到的,req 已更改。设置res.locals 不应更改req 对象...正确!?还是我错过了什么?
感谢您的帮助!
【问题讨论】:
标签: javascript node.js express locals