Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing token in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel

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)

like image 210
skyboyer Avatar asked Feb 13 '19 09:02

skyboyer


People also ask

How do I fix CORS header Access-Control allow Origin missing?

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.

How do you fix no Access-Control allow Origin header is present on the requested resource?

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.

How do I get rid of CORS error?

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.


1 Answers

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.

like image 97
sideshowbarker Avatar answered Oct 22 '22 23:10

sideshowbarker