我们有route
&这样middleware
:
当我们这样做时:
//middleware
router.use((req, res, next) => {
// check header or url parameters or post parameters for token
let token = req.body.token || req.query.token || req.headers['x-access-token'],
// verifies secret and checks exp
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.json({
success: false,
message: 'Failed to authenticate token.'
});
} else {
// if everything is good, save to request for use in other routes
res.locals.test = "test";
req.somevariable = "variable1";
console.log("res.locals.test inside middleware ", JSON.stringify(res.locals.test));
console.log("req.somevariable inside middleware ", JSON.stringify(req.somevariable));
next();
}
});
next();
});
//TestRoute
router.get('/TestRoute', (req, res) => {
console.log("res.locals.test outside middleware ", JSON.stringify(res.locals.test));
console.log("req.somevariable outside middleware ", JSON.stringify(req.somevariable));
});
req.somevariable
和res.locals.test
的值undefined
以外middleware
当我们这样做时:
//middleware
router.use((req, res, next) => {
res.locals.test = "test";
req.somevariable = "variable1";
console.log("res.locals.test inside middleware ", JSON.stringify(res.locals.test));
console.log("req.somevariable inside middleware ", JSON.stringify(req.somevariable));
next();
});
//TestRoute
router.get('/TestRoute', (req, res) => {
console.log("res.locals.test outside middleware ", JSON.stringify(res.locals.test));
console.log("req.somevariable outside middleware ", JSON.stringify(req.somevariable));
});
在req.somevariable
之外可以使用res.locals.test
和middleware
的值。
这里有什么问题?
答案 0 :(得分:1)
res.locals.VARIABLENAME = req.user
VARIABLENAME
(无论您将其设置为什么变量)在使用.ejs
或使用该变量进行动态渲染时都可能显示为未定义。您可能会得到错误,例如变量名未定义。>
这是res.locals
的一个奇特之处:当您想在渲染时使用设置为res.locals
的变量名时,必须在函数RENDERS the File中定义req.user
!
后端:res.locals.currentUser = req.user
//THIS FUNCTION WILL RENDER PERFECTLY LETTING ME USE currentUser in my .ejs file
upgradeForm(req, res, next) {
let saved = req.user;
if(req.user){
res.render("users/upgrade");
} else{
req.flash("notice", "You've successfully signed in!");
res.redirect("/");
}
}
但是
//THIS FUNCTION WILL SAY currentUser is UNDEFINED IN MY .ejs file
upgradeForm(req, res, next) {
if(req.user){
res.render("users/upgrade");
} else{
req.flash("notice", "You've successfully signed in!");
res.redirect("/");
}
}
除了工作功能渲染已将req.user
设置为变量之外,没有代码差异(您甚至不必使用该变量)。花了我9个小时来解决这个问题,但现在您知道了!