Javascript Express.js-设置res.locals会更改req对象
我很困惑这里发生了什么。我正在尝试为用户设置res.locals默认配置文件图片(如果他们当前没有)。这是我的密码:Javascript Express.js-设置res.locals会更改req对象,javascript,node.js,express,locals,Javascript,Node.js,Express,Locals,我很困惑这里发生了什么。我正在尝试为用户设置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: ',
// 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中的对象由指针指定。因此,当您这样做时:
res.locals.user = req.user;
现在,您的res.locals.user
和req.user
都指向完全相同的对象。如果然后通过其中一个修改该对象,则两个对象都指向同一个对象,这样两个对象都将看到更改
也许您要做的是将req.user
对象复制到res.locals.user
上,这样您就有了两个完全独立的对象,可以单独修改
在node.js中复制(或克隆)对象有多种机制,如下所示:
还有哦,哇……我真不敢相信我错过了。在这里,我认为这是一个表达的东西,当它是一个简单的JS的东西。这在JS中是一个很好的例子。谢谢你的帮助!答案被接受。