如何在 CORS 预检 OPTIONS 请求中发送自定义标头? [英] How do you send a custom header in a CORS preflight OPTIONS request?

查看:50
本文介绍了如何在 CORS 预检 OPTIONS 请求中发送自定义标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 JSON 有效负载发送 CORS 请求.我控制服务器和客户端.

I am trying to send a CORS request for a JSON payload. I control both the server and the client.

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

服务器有一个自定义标头,必须与每个请求一起发送.因此,此自定义标头使请求不简单",因此必须使用 OPTIONS 请求对请求进行预检.

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.

我可以看到 jquery 发出 OPTIONS 请求,但它没有发送自定义标头.

I can see jquery making the OPTIONS request, but it doesn't send the custom header along.

我尝试过的方法:

在这两种情况下,浏览器都不会发送自定义标头.

In both cases, the browser is not sending the custom header along.

我使用的是 FF 17.0.1,jquery 1.8.3.

I'm using FF 17.0.1, jquery 1.8.3.

推荐答案

你的问题不在于 jquery,而在于 CORS 的工作原理.您的 beforeSend 回调可能按预期工作......但无论如何浏览器都不会在预检请求中发送自定义标头.这是设计使然;预检请求的目的是确定允许用户代理(浏览器)发送超出 CORS 规范中定义的简单"内容的信息.因此,对于用户代理发送任何非简单数据(例如您的自定义标头)作为预检请求的一部分是弄巧成拙的.

Your problem isn't with jquery, it's in how CORS works. Your beforeSend callback was probably working as expected... but browsers won't send custom headers in preflight requests, no matter what. 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. Thus, for the useragent to send any non-simple data (such as your custom header) as part of the preflight request is self-defeating.

要指示用户代理在实际的 CORS 请求中包含您的自定义标头,请包含 Access-Control-Allow-Headers header 在您的预检响应中.值得注意的是,如果您不太关心用户代理传输的标头,我相信您可以将 Access-Control-Request-Headers 请求标头字段的值回显为您在响应中发送的 Access-Control-Allow-Headers.

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. 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.

您可能还希望包含在 规范的语法部分.

You may also want to include some of the other Access-Control-Allow-* headers defined in the syntax section of the spec.

另请参阅CORS - 如何预检"httprequest?

另请参阅 Mozilla 的 CORS 预检示例,其中显示了这些标题在行动.

See also Mozilla's CORS preflight example, which shows these headers in action.

这篇关于如何在 CORS 预检 OPTIONS 请求中发送自定义标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆