0

在快速 cookie 会话中定义 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 <<<

尝试在另一个路由中访问 c​​ookie:

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

>>> RETURNS 'token: undefined' <<<
4

1 回答 1

-1

首先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
})
于 2019-08-10T16:50:32.563 回答