Handling a 401 on the front end


I’ve a login method that ‘works’, but if a user doesn’t exist, or if the password is incorrect, my server responds using this code:

return res.status(401).json({ success: false, message: "Bad Username/Password" });

On the front end I’m using axios like this:

try {
    const res = await this.User.login(loginView.getLoginDetails());  
} catch(e) { 
     console.log("oh no" + e) 
export default class User {
    async login({ email, password }) {
        // JRS is just an axios create instance
        return await JRS.post('/auth/login', { email, password });

My question is, how do I handle a failed attempt to log in? It seems to just be returned as a 401 error, that I’m unsure how to deal with

even looking at the error object returned to me I can’t see anything useful. I must be doing something wrong…!


Edit: More on the error:

Definitely not the error message I sent from the server :man_shrugging:

Just posting the answer in case anyone comes across this:

if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);

Taken from here

Should it not be res.status(401).send("Bad Username/Password")?

I’d always thought there wasn’t much difference between the two?

Either way, my problem just seemed to be down to the fundamental way that Axios deals with responses - anything outside the 200 range seems to be dealt with as an error, but the details of that can be accessed on error.response. Seems odd to me, but what do I know :grin:

Ah, yeah it is the same, just been a while since I used Express. Have you checked that the reason you aren’t getting the error message you’ve specified isn’t just a CORs issue? Because in that case you’d still get the 401, just not the response message.

Afaics axios has something called interceptors that let you specify some arbitrary action/s for a specific response, but the catch should be working here

Yeah it was literally just that the response object was on the error object.

So error.response.data contained the json object I returned with the success and message attributes. Think you can change what axios classifies as an error too. :+1:

1 Like