Jon Doe
Jon Doe

Reputation: 389

Axios follow redirect

I currently have some JavaScript code in my front-end React application that makes get/post requests to my Express back-end with axios. My current back-end implementation can sometimes redirect to a different page if the input is invalid (to the login page in the following example)

//back-end logic
if(valid data) response.json(someData);
if(invalid data) response.redirect("/login");

My axios request is the following:

axios.get("some.url/api").then(res => {
    //work with the res.someData if valid
}
.catch(err => console.log(err))

The issue I am facing is that if axios receives the redirect response it fetches that page but I want to redirect the window to the redirected URL.

Is it possible to make axios redirect the user window to the redirected page with axios when it receives response.redirect('url') from Express?

Upvotes: 5

Views: 20833

Answers (1)

Quentin
Quentin

Reputation: 943220

No, it isn't.

The underlying API used by Axios in browsers follows redirects transparently.


Consider checking the content-type in the response and setting location to a new value if it is HTML rather than JSON.

Upvotes: 5

Related Questions