简体   繁体   English

如何在 CORS 预检 OPTIONS 请求中发送自定义标头?

[英]How do you send a custom header in a CORS preflight OPTIONS request?

I am trying to send a CORS request for a JSON payload.我正在尝试为 JSON 有效负载发送 CORS 请求。 I control both the server and the client.我控制服务器和客户端。

I'm following along here: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&redirectslug=HTTP_access_control我在这里关注: https ://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&redirectslug=HTTP_access_control

The server has a custom header that must be sent along with every request.服务器有一个自定义标头,必须与每个请求一起发送。 This custom header therefore makes the request 'not simple' and thus the request must be preflighted with an OPTIONS request.因此,此自定义标头使请求“不简单”,因此必须使用 OPTIONS 请求对请求进行预检。

I can see jQuery making the OPTIONS request, but it doesn't send the custom header along.我可以看到 jQuery 发出 OPTIONS 请求,但它没有发送自定义标头。

Methods I've tried:我试过的方法:

In both cases, the browser is not sending the custom header along.在这两种情况下,浏览器都不会发送自定义标头。

I'm using FF 17.0.1, jQuery 1.8.3.我正在使用 FF 17.0.1、jQuery 1.8.3。

Your problem isn't with jquery, it's in how CORS works .您的问题不在于 jquery,而在于 CORS 的工作方式 Your beforeSend callback was probably working as expected... but browsers won't send custom headers in preflight requests, no matter what.您的 beforeSend 回调可能按预期工作......但无论如何浏览器都不会在预检请求中发送自定义标头。 This is by design;这是设计使然; the purpose of the preflight request is to determine what information the useragent (browser) is permitted to send beyond the "simple" stuff defined in the CORS spec.预检请求的目的是确定允许用户代理(浏览器)发送超出 CORS 规范中定义的“简单”内容的信息。 Thus, for the useragent to send any non-simple data (such as your custom header) as part of the preflight request is self-defeating.因此,对于用户代理发送任何非简单数据(例如您的自定义标头)作为预检请求的一部分是弄巧成拙的。

To instruct the useragent to include your custom header in the actual CORS request, include a Access-Control-Allow-Headers header in your preflight response.要指示用户代理在实际的 CORS 请求中包含您的自定义标头,请在您的预检响应中包含一个Access-Control-Allow-Headers标头 It's worth noting that if you're not overly concerned with what headers the useragent transmits, I believe you can just echo back the value of the Access-Control-Request-Headers request header field as the value of the Access-Control-Allow-Headers you send in the response.值得注意的是,如果您不太关心用户代理传输的标头,我相信您可以将Access-Control-Request-Headers请求标头字段的值作为Access-Control-Allow-Headers的值回显。您在响应中发送的Access-Control-Allow-Headers

You may also want to include some of the other Access-Control-Allow-* headers defined in the syntax section of the spec .您可能还希望包含在规范的语法部分中定义的其他一些Access-Control-Allow-*标头。

See also CORS - How do 'preflight' an httprequest?另请参阅CORS - 如何“预检”httprequest?

See also Mozilla's CORS preflight example , which shows these headers in action.另请参阅Mozilla 的 CORS 预检示例,其中显示了这些标头的实际操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM