Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Axios have the ability to detect redirects?

The Response interface of the Fetch API has a read-only flag, redirected, which indicates whether or not the response was the result of a request that was redirected.

Does the axios library have a similar capability? The best I could find is maxRedirects which sets the maximum number of redirects to follow. However, I am simply looking to determine if it happened or not (so I can handle redirects specially), not prevent it from happening.

like image 723
Daniel Bank Avatar asked Apr 30 '19 17:04

Daniel Bank


People also ask

Can an API redirect?

redirect() The redirect() method of the Response interface returns a Response resulting in a redirect to the specified URL. Note: This is mainly relevant to the ServiceWorker API. A controlling service worker could intercept a page's request and redirect it as desired.

How do I follow redirects with curl?

To follow redirect with Curl, use the -L or --location command-line option. This flag tells Curl to resend the request to the new address. When you send a POST request, and the server responds with one of the codes 301, 302, or 303, Curl will make the subsequent request using the GET method.

Does XHR follow redirect?

Yes, XMLHttpRequest object (according to the standard) must automatically handle redirection without giving the client code a chance to do anything about it.

What is Axios JSON?

Axios is a promise-based HTTP client library that makes it simple to send asynchronous HTTP requests (such as POST , GET , and DELETE ) to REST endpoints, mainly APIs. In this article, we will learn how to send POST JSON requests with Axios, and how to handle both previously serialized and unserialized data.


2 Answers

Compare the request URL from your code with the URL given by response.request.responseURL; if those aren’t equal, you know the request was redirected.

As far as the status code being 200, that’s what’s required by the spec; no intermediate status codes are exposed to frontend JavaScript running in a browser — regardless of which API you use. See also the answer at http://stackoverflow.com/a/46031800/441757

like image 102
sideshowbarker Avatar answered Oct 06 '22 20:10

sideshowbarker


You can get the redirect count:

const response = await axios.get('http://someurlthatredirects.com');
console.log(response.request._redirectable._redirectCount);
like image 20
Populus Avatar answered Oct 06 '22 19:10

Populus