gpt4 book ai didi

javascript - 为什么 req.somevariable 和 res.locals 不能与 jwt 回调一起使用?

转载 作者:行者123 更新时间:2023-12-03 04:25:39 29 4
gpt4 key购买 nike

我们有一个路由和一个中间件,如下所示:

当我们这样做时:

//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.somevariableres.locals.test 的值在 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.somevariableres.locals.test 的值在middleware 外部可用。

这里有什么问题吗?

最佳答案

res.locals.VARIABLENAME = req.user

当您使用 .ejs 或使用该变量进行动态渲染时,

VARIABLENAME(无论您将其设置为什么变量)都可能显示为未定义,您可能会收到类似以下错误变量名未定义。

这对于 res.locals 来说是一个奇怪的现象:当您想在渲染中使用设置为 res.locals 的变量名称时,您必须定义 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 个小时才解决这个问题,但现在你知道了!

关于javascript - 为什么 req.somevariable 和 res.locals 不能与 jwt 回调一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43741157/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com