23

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.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Daniel Bank
  • 3,581
  • 3
  • 39
  • 50
  • Is it not sufficient to validate the response status reflects a redirection? – djfdev Apr 30 '19 at 17:54
  • So the redirected response status is 200, but it is bogus. I need to determine if it is a legitimate 200 or not. The Network tab shoes both the 302 and 200 requests but the fetch/axios call only shows 200 when handling the response – Daniel Bank Apr 30 '19 at 19:12

5 Answers5

22

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

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
  • 2
    -1 : As far as I can tell, the `response` exposed by axios does not have a `url` member which makes this a total non-answer to the question. https://github.com/axios/axios#response-schema – pooley1994 Sep 07 '20 at 17:09
  • 4
    I believe the value you want will be exposed at `response.request.responseURL` – Ben Zenker Sep 25 '20 at 00:19
  • Just keep in mind `response.request.responseURL` is not available when using Internet Explorer 11, at least with axios v.0.20.0. – Kasparas Anusauskas May 25 '21 at 13:25
  • 6
    in my case 'response.request.res.responseUrl' worked – ori888 Sep 06 '21 at 12:41
  • According to docs: "`request` is the request that generated this response. It is the last ClientRequest instance in node.js (in redirects) and an XMLHttpRequest instance in the browser". So there may be differences if you are checking the request in a browser or node, and there may also by differences between nodejs versions. Check documentation for you environment/version. – Cyrille Dec 31 '21 at 11:47
22

You can get the redirect count:

const response = await axios.get('http://someurlthatredirects.com');
console.log(response.request._redirectable._redirectCount);
Populus
  • 7,470
  • 3
  • 38
  • 54
2

I tried to access response sub-object in request object in Axios that was described in docs as

// `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {}

I didn't really understand what it means, so @ori888's comment worked with response.request.res.responseUrl, now I can redirect a client to that address, and it worked thank you ori888

2

Given answer didn't resolve my issue so adding my bit. To stop Axios from redirecting, set maxRedirects property to 0:

    axios({
          url: 'someurl.com',
          method: 'get',
          timeout: 20000,
          maxRedirects: 0,
          validateStatus: (status: number) =>
            status >= 200 && status < 400,
        })

validateStatus is used to accept the 3XX status codes as correct responses.

Dmitriy Popov
  • 2,150
  • 3
  • 25
  • 34
Pranoy Sarkar
  • 1,965
  • 14
  • 31
  • The maxRedirects option only works in Node.js, https://github.com/axios/axios/issues/674#issuecomment-279225530 – Hans Jul 11 '23 at 08:33
1

I found that maxRedirects-option only works in Node.js, as stated in this GitHub-issue here.

I then tried the beforeRedirect-option, which I found on the AxiosRequestConfig-type definitions. It didn't work either, probably due to the same reasons as maxRedirects didn't.

What I ended up doing is using interceptors like this:

import axios, { isAxiosError } from "axios";
import { hasOwnProperties, hasOwnProperty } from "utils";

//...

const axiosInstance = axios.create();
axiosInstance.interceptors.response.use(
  // Any status codes that lie within the range of 2xx (default), or do pass custom `validateStatus()` cause this function to trigger
  function (response) {
    if (
      hasOwnProperty(response, "request") &&
      hasOwnProperties(response.request, ["requestURL", "responseURL"]) &&
      response.request.requestURL !== response.request.responseURL
    ) {
      // do your stuff
    }
    return response;
  },
  // Any status codes that falls outside the range of 2xx cause (default), or do not pass custom `validateStatus()` this function to trigger
  function (error) {
    if (
      isAxiosError(error) &&
      error.response &&
      hasOwnProperties(error.response.request, ["requestURL", "responseURL"]) &&
      error.response.request.requestURL !== error.response.request.responseURL
    ) {
      // do your stuff
    }
  }
);

Hans
  • 1,162
  • 11
  • 18