无法从响应标头中的后端获取JWT令牌 [英] Not getting the JWT token from the backend in the Headers of the Response

查看:100
本文介绍了无法从响应标头中的后端获取JWT令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

启动登录并创建令牌(如果注册了用户并使用res.header函数发送令牌)时,我正在向前端(登录应用程序)发送令牌,但是当我记录响应时. strong>我只获得内容类型(我认为这是默认值),但是每当我尝试从邮递员登录时,我都会在标题部分获得令牌.

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

This is Code of my express backend server which is creating a token and sending it

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'});
  }
});

如果需要前端代码:

In case if the front-end code is required :

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 );
                    }
                )
        }
    },
};

推荐答案

仅应在发送请求时使用Authorization标头.不在回应中.尝试改为在响应的正文中返回授权:

The Authorization header should only be used when sending a request; not during a response. Try instead returning the authorisation in the body of the response:

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

这篇关于无法从响应标头中的后端获取JWT令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆