2015-09-23 43 views
-1

我很困惑在這裏發生了什麼。我正在嘗試爲用戶設置res.locals默認配置文件圖片,如果他們目前沒有。這裏是我的代碼:Express.js - 設置res.locals更改req對象

// 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對象...正確!?或者我錯過了什麼?

感謝您的幫助!

回答

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()

+0

哇哦......我無法相信我錯過了。在這裏,我認爲這是一個快速的事情,當它是一個簡單的JS事情。 JS就是這樣的「陷阱」。 感謝您的幫助!接受答案。 – Beau