自定义标头未在JQuery $ .ajax跨域请求中发送

时间:2014-11-06 14:10:59

标签: javascript jquery ajax cors

我正在设置IE 8和9的后备,我使用JQuery发送跨域GET请求。我正在使用IE 11在IE8和9的仿真模式下进行测试。

服务器已正确设置为CORS,并已使用纯JavaScript XMLHttpRequest进行跨域请求测试。

IE8 / 9上下文中的请求代码如下:

$.ajax({

        type:"GET",

        url: url,
        beforeSend : function(xhr) {

            xhr.setRequestHeader('Api-Version', config.apiVersion);
            xhr.setRequestHeader('Api-Account-Key', config.accountKey);
            xhr.setRequestHeader('Api-Authorisation-Key', config.authorisationKey);
        },
        success: function(data) {

            callback(data);
        }
});

当发送请求跨域(此时站点在非localhost域下运行)时,很明显没有发送自定义标头,这是 OPTIONS请求(来自Fiddler调试器的输出)。

    GET http://localhost:35000/api/example-url HTTP/1.1
    Accept: */*
    Origin: http://dev.local
    Accept-Language: en-GB
    Accept-Encoding: gzip, deflate
    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
    Host: localhost:35000
    DNT: 1
    Connection: Keep-Alive
    Pragma: no-cache

如果我使用相同的代码从同一域发送请求,则会按照我的预期设置标头。

GET http://localhost:35000/api/example-url HTTP/1.1
x-requested-with: XMLHttpRequest
Accept-Language: en-gb
Referer: http://localhost:35000/Documentation
access-control-request-headers: x-requested-with
api-account-key: xxxxxx
Accept: */*
api-version: 1.0
api-authorisation-key: xxxx
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Host: localhost:35000
DNT: 1

那么是什么阻止了JQuery,或者可能是浏览器在跨域上下文中发送标头?

1 个答案:

答案 0 :(得分:2)

Internet Explorer 8和9使用XDomainRequest API执行跨域请求。根据链接到IE9 jQuery AJAX with CORS returns "Access is denied"this jQuery feature request,jQuery开发团队肯定拒绝支持XDomainRequest,因为与XMLHttpRequest相比,它有太多缺点和不一致。< / p>

该答案还链接到plugin that allows the use of XDR in jQuery。请注意,它仍然会受到XDR的内置限制,因此即使您可以使用该插件让jQuery使用{{1},它也可能无法解决您的问题API。

相关问题