admin管理员组文章数量:1332705
I was wondering if using res.locals like in this code example is bad practice or if there can occur any problems if you use it this way:
app.use((req, res, next) => {
const session = req.cookies.session
if (session) {
db.admin.auth().verifySessionCookie(session, true)
.then((decodedData) => {
res.locals.userId= decodedData.uid
next();
})
.catch(() => {
res.locals.userId = false
next();
})
} else {
res.locals.userId = false
next();
}
app.get("/", async (req, res) => {
console.log(res.locals.userId)
res.render("home.hbs")
})
Basically I:
- I verify the session-cookie in app.use (Im using firebase auth)
- I set the res.locals.userId = userId
- And then use the local i just set in the app.get
(I need to do it this way because I need the userId in my view, otherwise I need to run the verifySessionCookie function 2 times to get the userId which I want to avoid)
I was wondering if using res.locals like in this code example is bad practice or if there can occur any problems if you use it this way:
app.use((req, res, next) => {
const session = req.cookies.session
if (session) {
db.admin.auth().verifySessionCookie(session, true)
.then((decodedData) => {
res.locals.userId= decodedData.uid
next();
})
.catch(() => {
res.locals.userId = false
next();
})
} else {
res.locals.userId = false
next();
}
app.get("/", async (req, res) => {
console.log(res.locals.userId)
res.render("home.hbs")
})
Basically I:
- I verify the session-cookie in app.use (Im using firebase auth)
- I set the res.locals.userId = userId
- And then use the local i just set in the app.get
(I need to do it this way because I need the userId in my view, otherwise I need to run the verifySessionCookie function 2 times to get the userId which I want to avoid)
Share Improve this question asked May 12, 2021 at 22:22 eekeek 572 silver badges7 bronze badges 1- What makes you think it would be bad practice? It's documented as being "useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on." – blex Commented May 12, 2021 at 22:26
1 Answer
Reset to default 8res.locals
is explicitly designed as a place for you to put things that later parts of the request handling want/need to use and it is often used for template rendering. So, this is precisely what it is supposed to be used for.
I was wondering if using res.locals like in this code example is bad practice or if there can occur any problems if you use it this way
No bad things will happen. This is exactly what res.locals
is for. See the doc reference for further confirmation.
本文标签: javascriptIs this bad practice for reslocals (NodejsExpress)Stack Overflow
版权声明:本文标题:javascript - Is this bad practice for res.locals? (Node.js, express) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742246169a2439653.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论