簡體   English   中英

Express.js - 設置 res.locals 會改變 req 對象

[英]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地方檢查req.user.profile.picture以更改圖片。

if (!req.user.profile.picture) {do stuff}

正如您在上面看到的, req已更改。 設置res.locals不應該改變req對象...正確!? 或者我錯過了什么?

謝謝你的幫助!

Javascript 中的對象是通過指針分配的。 所以,當你這樣做時:

res.locals.user = req.user;

現在res.locals.userreq.user指向同一個對象。 如果您隨后通過其中任何一個修改該對象,則兩者都指向同一個對象,因此兩者都會看到更改。

也許您想要做的是將req.user對象復制到res.locals.user以便您擁有兩個可以獨立修改的完全獨立的對象。

此處顯示的 node.js 中有多種復制(或克隆)對象的機制:

在 Node.js 中克隆一個對象

還有Object.assign()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM