简体   繁体   English

无法将身份验证令牌发送到服务器 axios

[英]Unable to send auth token to server axios

I am trying to set up a simple login system for a small project.我正在尝试为一个小项目设置一个简单的登录系统。 I have managed to connect the website to an login api hosted locally via mysql database.我设法将网站连接到通过 mysql 数据库在本地托管的登录 api。 I'm using express/nodejs on backend and Vue for front end.我在后端使用 express/nodejs,在前端使用 Vue。 Also using axios to send http requests.也使用 axios 发送 http 请求。

The error i get is POST http://localhost:3001/api/get-user 422 (Unprocessable Entity) "{"message":"Please provide the token"}" Client side part of code.我得到的错误是 POST http://localhost:3001/api/get-user 422 (Unprocessable Entity) "{"message":"Please provide the token"}" Client side part of code。

            finally{
            const auth = await axios.post(`/api/get-user`, {
                headers: {
                Authorization: `Bearer ${this.Token}` 
                }
            })
        }

Server side part.服务器端部分。

router.post('/get-user', signupValidation, (req, res, next) => {


if(
    !req.headers.authorization ||
    !req.headers.authorization.startsWith('Bearer') ||
    !req.headers.authorization.split(' ')[1]
){
    return res.status(422).json({
        message: "Please provide the token",
    });
}

const theToken = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(theToken, 'the-super-strong-secrect');

db.query('SELECT * FROM users where id=?', decoded.id, function (error, results, fields) {
    if (error) throw error;
    return res.send({ error: false, data: results[0], message: 'Fetch Successfully.' });
});

}); });

I have put a base URL.我已经放了一个基本网址。 The login is working 100% and I am able to extract the token from the response data.登录工作 100%,我能够从响应数据中提取令牌。 I used Postman to send the request to the server to get the user and it works perfectly.我使用 Postman 将请求发送到服务器以获取用户,并且效果很好。 I believe the issue is in the code of the client side or maybe the client side is sending the token incorrectly where the server side cant read it... I'm not sure please help.我相信问题出在客户端的代码中,或者客户端在服务器端无法读取的地方错误地发送了令牌......我不确定请帮忙。

The second parameter in axios post is the body axios post中的第二个参数是body

 finally{
            const auth = await axios.post(`/api/get-user`,{}, {
                headers: {
                Authorization: `Bearer ${this.Token}` 
                }
            })
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM