Backend returns
Access-Control-Allow-Headers: *
I have a request like
fetch('url-here', {
// ...
headers: {
'X-Auth': token,
}
})
It works in Chrome but for Firefox I'm getting
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at <...cut...>. (Reason: missing token ‘X-Auth’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).[Learn More] Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at <...cut...>. (Reason: CORS request did not succeed)
If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.
There Are Two Approaches to Getting It Right.Use a reverse proxy server or WSGI server(such as Nginx or Apache) to proxy requests to your resource and handle the OPTIONS method in the proxy. Add support for handling the OPTIONS method in the resource's code.
To get rid of a CORS error, you can download a browser extension like CORS Unblock ↗. The extension appends Access-Control-Allow-Origin: * to every HTTP response when it is enabled. It can also add custom Access-Control-Allow-Origin and Access-Control-Allow-Methods headers to the responses.
The problem is, some browsers don’t yet allow *
wildcards for Access-Control-Allow-Headers
. Notably, Firefox 69 and earlier doesn’t. See https://bugzilla.mozilla.org/show_bug.cgi?id=1309358.
So to ensure you get expected behavior in all browsers, the Access-Control-Allow-Headers
value you send back should explicitly list all the header names you actually need to access from your frontend code; e.g., for the case in the question: Access-Control-Allow-Headers: X-Auth
.
One way you can make that happen without needing to hardcode all the header names is: Have your server-side code take the value of the Access-Control-Request-Headers
request header the browser sends, and just echo that into the value of the Access-Control-Allow-Headers
response header your server sends back.
Or else use some existing library to CORS-enable your server. Echoing the Access-Control-Request-Headers
request-header value into the Access-Control-Allow-Headers
response-header value is something most CORS libraries will typically do for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With