Categories
React Answers

How to make redirects after an axios post request with Express and React?

Spread the love

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?”

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.