Express.js - 设置 res.locals 更改请求对象
Express.js - Setting res.locals changes the req object
我很困惑这里发生了什么。我正在尝试为用户设置 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中的对象由指针赋值。所以,当你这样做时:
res.locals.user = req.user;
您现在 res.locals.user
和 req.user
都指向完全相同的对象。如果您随后通过其中任何一个修改该对象,则两者都指向同一个对象,因此两者都会看到更改。
也许您想要做的是将 req.user
对象复制到 res.locals.user
,这样您就有了两个可以独立修改的完全独立的对象。
此处显示了 node.js 中用于复制(或克隆)对象的多种机制:
Cloning an Object in Node.js
我很困惑这里发生了什么。我正在尝试为用户设置 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中的对象由指针赋值。所以,当你这样做时:
res.locals.user = req.user;
您现在 res.locals.user
和 req.user
都指向完全相同的对象。如果您随后通过其中任何一个修改该对象,则两者都指向同一个对象,因此两者都会看到更改。
也许您想要做的是将 req.user
对象复制到 res.locals.user
,这样您就有了两个可以独立修改的完全独立的对象。
此处显示了 node.js 中用于复制(或克隆)对象的多种机制:
Cloning an Object in Node.js