【问题标题】:Not getting the JWT token from the backend in the Headers of the Response未从响应标头中的后端获取 JWT 令牌
【发布时间】:2020-11-30 11:07:14
【问题描述】:

如果用户已注册并使用 res.header 函数发送令牌,但当我登录 response.headers 我只得到内容类型(我认为这是默认值),但每当我尝试从邮递员登录时,我都会在标题部分获得令牌。

这是我的快速后端服务器的代码,它正在创建一个令牌 并发送它

router.post('/login', (req, res) => {
  let user = {email: req.body.email, password: req.body.password};
  if (validateUser(user)) {
    pool.query(
      'SELECT * FROM auth WHERE email = ($1) AND password = crypt(($2), password)',
      [user.email, user.password],
    )
    .then( (results) => {
      if(results.rows.length >= 1) {
        const token = jwt.sign({ name: results.rows[0].name, email: results.rows[0].email }, process.env.TOKEN_SECRET);
        console.log(results.rows[0].name + ' Logged In');
        res.header('Authorization', token );
        res.status(200).json({message: "Welcome! " + results.rows[0].name });
      }
    },
    ( error ) => {
      res.status(401).json({message: 'User Not Found'});
    }
   )
  }
  else {
    res.status(401).json({message: 'Invalid Credentials'});
  }
});

如果需要前端代码:

login() {
            this.axios.post( 'http://localhost:3000/users/login', {
                    email: this.email,
                    password: this.password
                } )
                .then(
                    ( response ) => {
                        console.log( response.headers );
                        this.$router.push( {path: '/register'} );
                    },
                    ( error ) => {
                        alert( error.response.data.message );
                    }
                )
        }
    },
};

【问题讨论】:

  • 我试过 res.status(200).header(...).end() 仍然没有任何效果

标签: express authentication axios jwt token


【解决方案1】:

Authorization 标头只能在发送请求时使用;不是在响应期间。尝试在响应正文中返回授权:

res.status(200).json({message: "Welcome! " + results.rows[0].name,token:token});

【讨论】:

    猜你喜欢
    • 2020-11-16
    • 2021-04-20
    • 2019-12-25
    • 2016-03-08
    • 2020-07-05
    • 2021-07-29
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多