且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

尽管有效的CORS配置,“在飞行前响应中Access-Control-Allow-Headers不允许请求标头字段Access-Control-Allow-Origin"

更新时间:2022-11-12 09:50:28

删除前端代码中添加 Access-Control-Allow-Origin 请求标头的部分.

Drop the part of your frontend code that adds a Access-Control-Allow-Origin request header.

切勿在前端JavaScript代码中添加 Access-Control-Allow-Origin 作为请求标头.

Never add Access-Control-Allow-Origin as a request header in your frontend JavaScript code.

唯一会产生的负面影响是,即使实际( GET POST 等),否则将不会触发预检.然后预检将失败,并显示以下消息:

The only effect that’ll ever have is a negative one, in that it’ll cause browsers to do CORS preflight OPTIONS requests even in cases when the actual (GET, POST, etc.) request from your frontend code would otherwise not trigger a preflight. And then the preflight will fail with this message:

在飞行前响应中,Access-Control-Allow-Headers不允许请求标头字段Access-Control-Allow-Origin

Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response

…,否则将失败,除非已将发出请求的服务器配置为发送 Access-Control-Allow-Headers:Access-Control-Allow-Origin 响应标头.

…that is, it’ll fail with that unless the server the request is being made to has been configured to send an Access-Control-Allow-Headers: Access-Control-Allow-Origin response header.

但是您永远不需要 Access-Control-Allow-Headers 响应标头值中的 Access-Control-Allow-Origin .如果最终使一切正常,那实际上是在解决错误的问题.因为真正的解决方法是:永远不要将 Access-Control-Allow-Origin 设置为请求标头.

But you never want Access-Control-Allow-Origin in the Access-Control-Allow-Headers response-header value. If that ends up making things work, you’re actually just fixing the wrong problem. Because the real fix is: never set Access-Control-Allow-Origin as a request header.

直觉上,将其视为似乎合乎逻辑.我在请求和响应中都设置了 Access-Control-Allow-Origin ,因此应该比仅在响应中添加更好".但是实际上比在响应中设置它要糟糕(由于上述原因).

Intuitively, it may seem logical to maybe look at it as "I’ve set Access-Control-Allow-Origin both in the request and in the response, so that should be better than just having it in the response" — but it’s actually worse than only setting it in the response (for the reasons described above).

因此,最重要的是: Access-Control-Allow-Origin 仅是响应标头,而不是请求标头.因此,您只想在服务器端响应代码中进行设置,而不是在前端JavaScript代码中进行设置.

So the bottom line: Access-Control-Allow-Origin is solely a response header, not a request header. So you only ever want to set it in server-side response code, not frontend JavaScript code.

问题中的代码还试图添加 Origin 标头.您也永远不想尝试在前端JavaScript代码中设置该标头.

The code in the question was also trying to add an Origin header. You also never want to try to set that header in your frontend JavaScript code.

Access-Control-Allow-Origin 标头不同, Origin 实际上是一个请求标头-但它是一个特殊的标头,完全由浏览器控制,并且浏览器永远不会允许您的前端JavaScript代码进行设置.所以永远不要尝试.

Unlike the case with the Access-Control-Allow-Origin header, Origin is actually a request header — but it’s a special header that’s controlled completely by browsers, and browsers won’t ever allow your frontend JavaScript code to set it. So don’t ever try to.