使用jQuery将访问控制请求标头添加到AJAX请求的标头中
我想向jQuery的AJAX POST请求添加自定义标头.
I would like to add a custom header to an AJAX POST request from jQuery.
我已经尝试过:
$.ajax({
type: 'POST',
url: url,
headers: {
"My-First-Header":"first value",
"My-Second-Header":"second value"
}
//OR
//beforeSend: function(xhr) {
// xhr.setRequestHeader("My-First-Header", "first value");
// xhr.setRequestHeader("My-Second-Header", "second value");
//}
}).done(function(data) {
alert(data);
});
当我发送此请求并使用FireBug观看时,看到以下标头:
When I send this request and I watch with FireBug, I see this header:
选项xxxx/yyyy HTTP/1.1
主持人:127.0.0.1:6666
用户代理:Mozilla/5.0(Windows NT 6.1; WOW64; rv:11.0)Gecko/20100101 Firefox/11.0
接受:text/html,application/xhtml + xml,application/xml; q = 0.9,/; q = 0.8
接受语言:fr,fr-fr; q = 0.8,en-us; q = 0.5,en; q = 0.3
接受编码:gzip,deflate
连接:保持活动状态
来源:null
访问控制请求方法:POST
访问控制请求标头:我的第一标头,我的第二标头
语法:无缓存
缓存控制:无缓存
OPTIONS xxxx/yyyy HTTP/1.1
Host: 127.0.0.1:6666
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Origin: null
Access-Control-Request-Method: POST
Access-Control-Request-Headers: my-first-header,my-second-header
Pragma: no-cache
Cache-Control: no-cache
为什么我的自定义标头转到Access-Control-Request-Headers
:
Why do my custom headers go to Access-Control-Request-Headers
:
访问控制请求标头:我的第一个标头,我的第二个标头
Access-Control-Request-Headers: my-first-header,my-second-header
我期望这样的标头值:
My-First-Header:第一个值
My-Second-Header:第二个值
My-First-Header: first value
My-Second-Header: second value
有可能吗?
您在Firefox中看到的不是实际的请求;而是在Firefox中看到的.请注意,HTTP方法是OPTIONS,而不是POST.浏览器实际上是飞行前"请求,以确定是否应允许跨域AJAX请求:
What you saw in Firefox was not the actual request; note that the HTTP method is OPTIONS, not POST. It was actually the 'pre-flight' request that the browser makes to determine whether a cross-domain AJAX request should be allowed:
飞行前请求中的Access-Control-Request-Headers标头包括实际请求中的标头列表.然后,在浏览器提交实际请求之前,服务器将报告在此上下文中是否支持这些标头.
The Access-Control-Request-Headers header in the pre-flight request includes the list of headers in the actual request. The server is then expected to report back whether these headers are supported in this context or not, before the browser submits the actual request.