To make redirects after an axios post request with Express and React, we set window.location
to the new URL value after the response from the axios request to the Express back end is available.
For instance, we write
import React, { Component } from "react";
//...
class MyClass extends Component {
onSubmit = async (e) => {
e.preventDefault();
const { username, password } = this.state;
const response = await axios.post("/login", { username, password });
if (response.data.redirect == "/") {
window.location = "/index";
} else if (response.data.redirect == "/login") {
window.location = "/login";
}
};
//...
}
export default MyClass;
to create the onSubmit
method that calls axios.post
to make a POST request to the /login
endpoint in our Express back end,
Then we get the response
which has the redirect URL.
And then we set window.location
to a new value to go to the URL.
One reply on “How to make redirects after an axios post request with Express and React?”
That was really helpful, thanks a lot.