Search code examples
javascripthttp-redirectheaderxmlhttprequestfetch

How to read redirect URL from 3xx fetch response?


I am attempting to read the redirect URL from a 3xx redirect. (I'm planning on just reading the location: https://myredirectedurl.com header and handling it myself in JS. However when I make the fetch request i recieve

Access to fetch at 'https://myredirectedurl.com' (redirected from 'https://localhost:8000/somepath') from origin 'https://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I know why this error is raised and I do understand how CORS works. However I do not want the fetch function to execute the redirect.

I read on this stackoverflow question that the redirect: 'manual' property may help if it is set. This does stop the CORS error from appearing and stops the redirected request, however I am now unable to read the location: https://myredirectedurl.com header. I wish to read this so I can handle the redirect based on my application logic and then possibly use window.location.replace


Solution

  • I just wanted to update incase anyone stumbles here from a search engine. It is not possible. The browser transparently redirects before the client javascript can even interact with it. The recomended way to handle this is to use som 2xx status for the redirect and then read the redirect url from either a header or the content.