本文介绍了无法从响应标头中的后端获取JWT令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的快速后端服务器的代码,该代码正在创建令牌并发送
This is Code of my express backend server which is creating a tokenand 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'});
}
});
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令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!