1
votes

I'm having a problem using Axios with my backend. It's probably a very simple fix as I'm new to this.

Postman: The correct response is received for both valid and invalid credentials.

Axios: The correct response is received for valid crendentials, but the axios method's catch block is run when invalid credentials are entered.

authController.js:

exports.login = (req, res, next) => {
    const email = req.body.email;
    const pass = req.body.password;
    let loadedUser;

    User.findOne({ where: { email: email } })
        .then(user => {
            if(!user) {
                const error = new Error('Incorrect username or password');
                error.statusCode = 401;
                throw error;
            } else {
                loadedUser = user;
                return bcrypt.compare(pass, user.password);
            }
        })
        .then(isEqual => {
            if(!isEqual) {
                const error = new Error('Incorrect username or password');
                error.statusCode = 401;
                throw error;
            } else {
                const token = jwt.sign(
                    {
                        email: loadedUser.email,
                        userId: loadedUser.id
                    }, 
                    process.env.JWT_SECRET,
                    { expiresIn: '1hr' }
                );
                res.status(200).json({ token: token, userId: loadedUser.id });
            }
        })
        .catch(err => {
            if (!err.statusCode)
                err.statusCode = 500;
            next(err);
        });

};

The error handler in app.js. It seems to log the error correctly when incorrect credentials are entered, even with axios:

app.use((error, req, res, next) => {
    const status = error.statusCode || 500;
    const message = error.message;
    const data = error.data || 'No Data';

    console.log(status, message, data);

    res.status(status).json({message: message, data: data});
});

But then the axios catch block runs, so instead of receiving the json message, I get the following error

login(email, password) {
    const headers = {
        'Content-Type': 'application/json'
      };

      const data = JSON.stringify({
        email: email,
        password: password
      });

      axios.post('http://127.0.0.1:8080/auth/login', data, { headers })
          .then(res => console.log(res))
          .catch(err => console.log(err));

}

The error in the console for invalid credentials: Error in console Clicking the link highlighted opens a new page stating: "Cannot GET /auth/login", but I'm obviously making a post request, & I've added post to the form (just in case)

Any ideas what I could be missing?

Thanks

1

1 Answers

1
votes

Actually your code works fine but Axios will reject the promise of the call if you have the status 401. If you have a status between 200 to 300 it will resolve the promise.

There two ways to deal with this.

Check status in the catch block.

axios.post('http://127.0.0.1:8080/auth/login', data, {
    headers
  })
  .then(res => console.log(res))
  .catch(err => {
    if (err.response.status === 401) {
      //Auth failed
      //Call reentry function
      return;
    }
    return console.log(err)
  });

or change the validateStatus option;

axios.post('http://127.0.0.1:8080/auth/login', data, {
    headers,
    validateStatus: function (status) {
       return status >= 200 && status < 300 || (status === 401);
    },
  })
  .then(res => console.log(res))
  .catch(err => return console.log(err));