'React: CORS error when API 302 redirects to same domain
I have a React web app (a.com) that communicates with an API (b.api) via axios/XHR requests.
Now there is a specific request that the server answers with a 302 redirect to another a.com location. This fails with a CORS error in Chrome:
Access to XMLHttpRequest at 'https://a.com/redirectpath' (redirected from 'https://b.api/requestpath') from origin 'https://a.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Contrary to the error message, the preflight request of the triggered redirect seems to have origin: null set. Is this the problem? Why does this happen, if the redirect goes to the same domain the user is on (a.com)?
Thank you for any ides!
Solution 1:[1]
From what I understood, this is what happened:
- Browser makes a cross-origin request with
Authorizationheader tob.api. - The
Authorizationheader necessitates a preflight request, which is successful. - The response from
b.apiis a 302 redirect toa.com. - The browser makes the redirected request to
a.com, which includes the sameAuthorizationheader again. - Although this request goes to the same origin, it is still considered cross-origin because it was triggered by a redirect from a different origin.
- The
Authorizationheader therefore necessitates a preflight request toa.com, withOrigin: null. - This second preflight request is unsuccessful:
a.comdoes not returnAccess-Control-Allow-Origin(norAccess-Control-Allow-Headers: Authorization).
I think the problem is the behavior of b.api: A request that requires an Authorization header should not lead to a 302 response, because that carries over the Authorization header (and with it the credential!) to a different server.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Heiko Theißen |
