1

After sending an axios post request from react to the server when trying to add an if case for the res.status === 401 the app ignores it, it is though handling the cases for status code 200. Trying to deal with this for a few days now and haven't come to a solution.

const login = () => {
            axios({
              method: "POST",
              data: {
                email: loginEmail,
                password: loginPassword
              },
              withCredentials: true,
              url: "http://localhost:3000/login"
            }).then((res) => {
              if (res.status === 401) {
              console.log(res.status);
              toast.error("Something went wrong!");
              } else {  
              handleData(res.data);
              handleLoggedOut(false);
              toast.success("You are now logged in!");
              }
            });
        };

Tried different options like: if (!res) or if (res.error), even if(res.status = "401 (Unauthorized)") although the code is clearly 401 but nothing seems to work, seems like the only response recognized is the one with status 200, for a successfull login the function does its job but in case of an unsuccessfull one nothing happens, just the error with status 401 in the console.

If anyone has any ideas why this is happening please let me know.

Thanks in advance!

2
  • 1
    Does this answer your question? Handling Axios error in React Commented Mar 25, 2022 at 11:17
  • 1
    Axios isn't fetch, its API is different - it throws an error on non-2xx response status. Commented Mar 25, 2022 at 11:30

1 Answer 1

0

To handle request errors with axios you need to use the catch statement like this:

const login = () => {
  axios({
    method: "POST",
    data: {
      email: loginEmail,
      password: loginPassword
    },
    withCredentials: true,
    url: "http://localhost:3000/login"
  }).then((res) => {
    // request success
    console.log(res)
  }).catch((error) => {
    // request error
    console.log(error)
  });
};

You can see more examples in its Github page: https://github.com/axios/axios#example

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much! This solved my problem. I'm enrolled in a course and just getting the hang of it and sometimes even the tiniest of errors give me massive headaches haha, thanks a lot! @Bikas
You are welcome @PaulAdonis, please consider accepting and upvoting this answer if it solved your problem.
I've tried to do so but I'm not allowed to do so as I'm new to stackoverflow, my reputation is under 15 points and I'm not allowed yet but once I will I'll sure do it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.