-1

我很困惑这里发生了什么。如果用户当前没有,我正在尝试为用户设置 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对象...正确!?还是我错过了什么?

谢谢你的帮助!

4

1 回答 1

2

Javascript 中的对象是通过指针分配的。所以,当你这样做时:

res.locals.user = req.user;

您现在拥有两者res.locals.userreq.user指向完全相同的对象。如果您随后通过其中任何一个修改该对象,则两者都指向同一个对象,因此两者都会看到更改。

也许您想要做的是将req.user对象复制到,res.locals.user以便您拥有两个可以独立修改的完全独立的对象。

在 node.js 中有多种复制(或克隆)对象的机制,如下所示:

在 Node.js 中克隆对象

还有Object.assign()

于 2015-09-23T01:13:06.383 回答