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

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

问题描述

我正在尝试发送针对JSON负载的CORS请求.我同时控制服务器和客户端.

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

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

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

我尝试过的方法:

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

我正在使用FF 17.0.1,jQuery 1.8.3

解决方案

您的问题与jquery无关,它在

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

您可能还想包括在语法部分中定义的其他一些Access-Control-Allow-*标头规格.

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

另请参见 Mozilla的CORS预检示例,其中显示了这些内容标头在起作用.

I am trying to send a CORS request for a JSON payload. 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

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.

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

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.

解决方案

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.

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.

See also CORS - How do 'preflight' an httprequest?

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

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

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