如何在跨网域(CORS)XMLHttpRequest中发送自定义标头? [英] How do you send a custom header in a cross-domain (CORS) XMLHttpRequest?

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

问题描述

我想发送一个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.

我尝试的方法:

  • using the beforeSend option: http://api.jquery.com/jQuery.ajax/
  • using an ajax prefilter: http://api.jquery.com/jQuery.ajaxPrefilter/

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

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.

推荐答案

CORS如何工作。您的beforeSend回调可能正常工作正常...但浏览器不会发送自定义标头在预检请求,无论什么。这是设计;预检请求的目的是确定允许用户代理(浏览器)发送超出CORS规范中定义的简单内容的信息。因此,对于useragent发送任何非简单数据(例如您的自定义头)作为预检请求的一部分是自毁的。

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.

要指示useragent请在实际的CORS请求中添加您的自定义标题,包括 Access-Control-Allow-Headers 。值得注意的是,如果你不过分关心useragent发送的头部,我相信你可以回显 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.

也希望包括 Access-Control-Allow - * /#syntax>规范的语法部分

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)XMLHttpRequest中发送自定义标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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