'Axios.all() POST request is not catching errors
I am creating a sign up page in react.js that requires two different axios post requests. I put both of the them in axios.all(). This is my code:
axios
.all([
axios.post(
"https://api.chatengine.io/users/",
{ username: userName, secret: password }, // Body object
{ headers: authObject } // Headers object
),
axios.post("http://localhost:4000/register", {
email: email,
password: password,
username: userName,
}),
])
.then((res) => {
if (res.data === "User With Email Already Exists") {
setError("User With Email Already Exists");
console.log(res);
} else {
navigate("/login");
}
});
For the most part it works completely fine. However, when a user signs up and puts in an email that already exists in my database, it does not throw the error that says "User with email already exists." It just does nothing. In the console it will say Failed to load resource: the server responded with a status of 400 () and Uncaught (in promise) Error: Request failed with status code 400. So there is clearly an error and the error message I have set does not display. When I had two separate axios calls it was able to display the error message with no issue, so what changed? Any help would be appreciated!
Solution 1:[1]
anything other than 2xx responses goes to "catch" in axios library. your api is responding with 400 so what you can do is:
axios
.all([
axios.post(
"https://api.chatengine.io/users/",
{ username: userName, secret: password }, // Body object
{ headers: authObject } // Headers object
),
axios.post("http://localhost:4000/register", {
email: email,
password: password,
username: userName,
}),
])
.then((res) => {
navigate("/login");
})
.catch((e) => {
if (e.response?.data === "User With Email Already Exists") {
setError("User With Email Already Exists");
console.log(e):
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arshia Moghaddam |
