gpt4 book ai didi

javascript - Node 中的条件应用程序使用 - 快速

转载 作者:行者123 更新时间:2023-11-30 12:07:53 25 4
gpt4 key购买 nike

是否可以在 app.js 中有条件地使用 app.use? express cookie-session可以not change the value of maxAge dynamically我正在考虑做这样的事情,但我遇到了一些错误:

app.use(function(req,res,next ){
if(typeof req.session == 'undefined' || req.session.staySignedIn === 'undefined'){
//removing cookie at the end of the session
cookieSession({
httpOnly: true,
secure: false,
secureProxy: true,
keys: ['key1', 'key2']
});
}else{
//removing cookie after 30 days
cookieSession({
maxAge: 30*24*60*60*1000, //30 days
httpOnly: true,
secure: false,
secureProxy: true,
keys: ['key1', 'key2']
});
}
next();
});

而不是正常使用它:

app.use(cookieSession({
httpOnly: true,
secure: false,
secureProxy: true,
keys: ['key1', 'key2']
}));

现在我收到以下错误:

Cannot read property 'user' of undefined

我相信它指的是这一行(虽然它没有说具体在哪里)

req.session.user;

最佳答案

Express 中的中间件是一个函数,例如 function (req, res, next) {}。在您的示例中,cookieSession(options) 将返回这样一个函数,但在您的中间件中您不运行该函数,您忽略了 cookieSession 的返回值 - 即中间件你想跑。然后运行 ​​next()

您要做的是在您的条件中间件中执行实际的中间件,我们称之为条件中间件。像这样:

app.use(function (req, res, next) {
var options = {
httpOnly: true,
secure: false,
secureProxy: true,
keys: ['key1', 'key2']
};

if(typeof req.session == 'undefined' || req.session.staySignedIn === 'undefined') {
options.maxAge = 30*24*60*60*1000; // 30 days
}

return cookieSession(options)(req, res, next);
});

关于javascript - Node 中的条件应用程序使用 - 快速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34654765/

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