Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

javascript - 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...