Home > Enterprise >  Unable to send auth token to server axios
Unable to send auth token to server axios

Time:07-18

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. I'm using express/nodejs on backend and Vue for front end. Also using axios to send http requests.

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.

            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. I used Postman to send the request to the server to get the user and it works perfectly. 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.

CodePudding user response:

The second parameter in axios post is the body

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