As far as why the code can’t just check response.status: In the case of redirects, that will be the status code of whatever response ultimately comes back as the result of any redirects.
So if redirects end up taking things somewhere that returns a 200, then response.status will just be 200. No intermediate status codes are exposed to frontend JavaScript running in a browser—as the previous (very good) answer posted here already points out.
This does give me a lot of information, especially it tells me via:
response.redirected
It’s worth noting: to just detect if there’s been a redirect, you actually don’t even need to check that. That’s the easiest way to check, but you could also just check response.url, and if that’s different from the request URL you gave to the fetch(…)
call, you know it was redirected.
That used to be the typical way to check before response.redirected was first introduced.
Also worth noting: redirect: 'true'
in the code in the question isn’t valid; it’ll cause the code to fail prematurely. See https://developer.mozilla.org/en-US/docs/Web/API/Request/redirect:
Value A RequestRedirect
enum value, which can be one the following strings:
So what the code in the question seems to intend is redirect: 'follow'
. But that’s actually the default for redirect
, so you don’t need to explicitly specify it and can instead just omit it.
As far as the other redirect
values: As explained in an answer to another question here at Stack Overflow, you almost certainly never want to specify manual
except for some Service Worker cases. And error
means to treat any redirect as a network error.
In that case, for the code in the example, redirect: 'true'
would cause the catch
to get hit and you’d have no access to any details of the response, including whether it got redirected.
So to loop back to your original question:
I want to fetch an URL and determine what status code it has, especially if it has an HTTP 301 or HTTP 302 status code
…the answer is that for redirected requests there really is no way from frontend JavaScript code running in a browser to detect the exact status codes of any redirect.
So if you need to know the exact status code for any redirects that may happen for a request to a given URL, you must make the request from backend code, and handle the response there.