Express Cookie会话“未定义”

时间:2019-08-10 14:06:24

标签: node.js express cookies cookie-session

在快速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 <<<

尝试通过另一条路径访问Cookie:

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

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

1 个答案:

答案 0 :(得分:-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
})