語境
我res.locals.loggedUser在服務器中像這樣存盤整個用戶物件:
app.use(async (req, res, next) => {
const user = await User.findById(req.session.userid);
res.locals.loggedUser = user;
next();
});
設定后res.locals.loggedUser,我可以ejs像這樣在客戶端訪問它:
<% if(loggedUser) { %>
<p>Your name: <%= loggedUser.name %></p>
<% } %>
整個用戶物件由以下欄位組成:
_id: {
ObjectId("123abc")
},
name: {
type: String,
required: [true, 'Your name is required.']
},
email: {
type: String,
required: [true, 'Email cannot be blank.'],
unique: true
},
phone: {
type: Number,
required: [true, 'You must provide your phone number.'],
unique: true
},
hashpassword: String,
date: {
joined: {
type: Date
}
},
題
客戶能否像hashpassword欄位一樣訪問用戶物件的其余欄位?還是res.locals只對服務器可用?
謝謝你!
uj5u.com熱心網友回復:
客戶端可以訪問 res.locals 嗎?
不。
res.locals 僅存在于服務器上 - 它對客戶端不可用。
res.locals您的服務器端模板/模板引擎可以在構建網頁時使用的內容,就像您已經使用的<% if(loggedUser) { %>那樣將發送到客戶端,但res.locals網頁中不會有任何內容,除非您專門向您的將某些內容res.locals插入網頁的模板。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/366575.html
上一篇:使用nodejs創建動態路由
