访问控制请求标头,使用 jQuery 添加到 AJAX 请求的标头中 [英] Access Control Request Headers, is added to header in AJAX request with jQuery

查看:46
本文介绍了访问控制请求标头,使用 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
连接:保持连接
来源:空
访问控制请求方法: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

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 中看到的不是实际请求;请注意,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:

http://www.w3.org/TR/cors/

飞行前请求中的 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.

这篇关于访问控制请求标头,使用 jQuery 添加到 AJAX 请求的标头中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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