I have a case where I’m calling fetch()
and if the response is a 302 Redirect, I want to redirect the calling page to wherever it redirects to instead of following the redirect to retrieve the data.
The scenario is that the user does something on a page which is going to do a fetch to retrieve something to update on the page. But if their login session has expired, the server is going to return a 302 Redirect to the login page. My Javascript is expecting a JSON response back, but instead fetch
follows the redirect and it gets an HTML page.
What I really want to do is check if the response.status
is 302, get the URL that the redirect pointed to and set window.location
.
According to the documentation, I should be able to set redirect: "manual"
, then if the response.redirected
is true redirect to response.url
, or some say to retrieve the location
header from the response
But none of that works.
response.redirected
is never true.response.status
is zero.response.url
is the URL of the page that made the call, not where it was redirected to.- The
location
header is null.
The only thing that seems to work is that the Network tab shows that the server returned a 302 status.
Here’s my code:
fetch("url-that-forces-a-redirect", {
method: "POST",
redirect: "manual",
body: formData
}).then((response) => {
console.log("Response had status " + response.status);
if (response.redirected) {
var redirectedUrl = response.headers.get('location');
console.log("Got redirect: location header = " + redirectedUrl);
console.log(" response.url = " + response.url);
// window.location = redirectedUrl;
return;
}
});
Is there any way to do this?
BTW, I tried doing this with XMLHttpRequest first and couldn’t find a way to do it there either.