【问题标题】:Express.js - Setting res.locals changes the req objectExpress.js - 设置 res.locals 会改变 req 对象
【发布时间】: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


    【解决方案1】:

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

    res.locals.user = req.user;
    

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

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

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

    Cloning an Object in Node.js

    还有Object.assign()

    【讨论】:

    • 哦哇...我不敢相信我错过了。在这里,当它是一个简单的 JS 事物时,我认为这是一个 Express 事物。这就是 JS 中的一个“陷阱”。谢谢您的帮助!已接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多