快速饼干会话'undefined'



在快速 cookie 会话中定义 cookie 后,我可以轻松地将其登录到控制台。但是,当我尝试在应用程序的另一条路由中访问此cookie时,它会返回"未定义"。

设置饼干:

router.get('/callback', catchAsync(async (req, res) => {
console.log("in /callback");
if (!req.query.code) throw new Error('NoCodeProvided');
const code = req.query.code;
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
var response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
{
method: 'POST',
headers: {
Authorization: `Basic ${creds}`,
},
});
var json = await response.json();
req.session.token = json.access_token
console.log(req.session.token)
>>> RETURNS THE TOKEN CORRECTLY <<<

尝试通过其他路由访问 Cookie:

router.get('/loggedin', catchAsync(async (req, res) => {
console.log("/loggedin");
console.log("token: " + req.session.token);
>>> RETURNS 'token: undefined' <<<

在第一个router.get('/callback'..)中,catchAsync()函数不是全局声明的。它只处理这个特定的路由,实际上并不需要名称。

您应该将此功能包装在中间件中或创建一个全局可用的函数,我不知道目标是什么,但这里是 2 选项。

选项 1 将功能作为中间件启动。行为取决于您放置它的位置!!!也许在这种情况下并不完全有意义,但你可以玩一玩,但我认为你会明白的。

// if you put before your router initiation it is going to have effect on all of the routes
app.use(async(req, res, next) => {
if (!req.query.code) throw new Error('NoCodeProvided');
const code = req.query.code;
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
var response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
{
method: 'POST',
headers: {
Authorization: `Basic ${creds}`,
},
});
var json = await response.json();
req.session.token = json.access_token
console.log(req.session.token)
// 
// and you can do whatever want to do
// but have to call next
//
next()
})
// and your router looks like
router.get('/callback', (req, res) => {
// do what have to do
})

选项 2 - 声明中间件并在所需位置使用

// defining this middleware somewhere in the code
const catchAsync = async(req, res, next) => {
if (!req.query.code) throw new Error('NoCodeProvided');
const code = req.query.code;
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
var response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
{
method: 'POST',
headers: {
Authorization: `Basic ${creds}`,
},
});
var json = await response.json();
req.session.token = json.access_token
console.log(req.session.token)
// 
// and you can do whatever want to do
// but have to call next
//
next()
}
router.get('/callback', catchAsync, (req, res) => {
// do what have to do
})
router.get('/loggedin', catchAsync, (req, res) => {
// do what have to do
})

相关内容

最新更新