When using the fetch() function to perform a POST request to a server that responds with a RedirectResponse, the redirect will be automatically followed on the client side. This is because the redirect mode is set to follow by default in the fetch() function. As a result, the user will not be redirected to the new URL, but rather fetch() will follow that redirection behind the scenes and return the response from the redirect URL.
To overcome this, you can check whether the response is the result of a request that you made which was redirected. If so, you can retrieve the url property of the response, which will return the final URL obtained **after** any redirects, and using JavaScript's window.location.href, you can redirect the user to the target URL (i.e., the redirect page). Instead of window.location.href, one can also use window.location.replace(). The difference from setting the href property value is that when using the location.replace() method, after navigating to the given URL, the current page will not be saved in session history—meaning the user won't be able to use the back button to navigate to it.
Example code:
document.getElementById("myForm").addEventListener("submit", function (e) {
e.preventDefault(); // Cancel the default action
var formElement = document.getElementById("myForm");
var data = new FormData(formElement);
fetch("http://my-server/login", {
method: "POST",
redirect: "follow", // Change it to "manual" if you want to handle redirects manually
body: data,
})
.then((res) => {
if (res.redirected) {
window.location.href = res.url; // or, location.replace(res.url);
return;
} else {
return res.text();
}
})
.then((data) => {
document.getElementById("response").innerHTML = data;
})
.catch((error) => {
console.error(error);
});
});
Note: If you are using a cross-origin request, you will need to set the Access-Control-Expose-Headers response header on the server side to include the Location header. This is because only the CORS-safelisted response headers are exposed by default.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3