指定标头时,jQuery AJAX 无法工作(发出 OPTIONS 飞行前请求)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21023454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:23:49  来源:igfitidea点击:

jQuery AJAX fails to work (OPTIONS pre-flight request made) when headers are specified

jqueryajaxhttp-headers

提问by Deepak Thomas

The AJAX request works fine, but the moment I add a header via beforeSend or headers, an OPTIONS pre-flight request is made and the GET request is aborted.

AJAX 请求工作正常,但是当我通过 beforeSend 或 headers 添加标头时,会发出一个 OPTIONS 飞行前请求并中止 GET 请求。

  Code: $.ajax({
        type: "GET",
        crossDomain: true,
         beforeSend: function (xhr)
         {
         xhr.setRequestHeader("session", $auth);
         },
        url: $url,
        success: function (data) {
            $('#something').html(data);
        },
        error: function (request, error) {
            $('#something').html("<p>Error getting values</p>");
        }
    });

SimilarAJAX Request w/o headers specified (the moment I add/modify header, an OPTIONS call is made)

没有指定标头的类似AJAX 请求(在我添加/修改标头的那一刻,进行了 OPTIONS 调用)

Request GET /api/something?filter=1 HTTP/1.1
Referer http://app.xyz.dj/dashboard
Accept  application/json, text/javascript, */*; q=0.01
Accept-Language en-US
Origin  http://app.xyz.dj
Accept-Encoding gzip, deflate
User-Agent  Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MASMJS; rv:11.0) like Gecko
Host    162.243.13.172:8080
DNT 1
Connection  Keep-Alive
Cache-Control   no-cache

Similar Server Response Header (for GET request)

类似的服务器响应头(用于 GET 请求)

Response    HTTP/1.1 200 OK
Server  Apache-Coyote/1.1
Access-Control-Allow-Origin *
Access-Control-Allow-Methods    GET, POST, DELETE, PUT, OPTIONS, HEAD
Access-Control-Allow-Headers    Content-Type, Accept, X-Requested-With
Access-Control-Allow-Credentials    true
Content-Type    application/json
Transfer-Encoding   chunked
Date    Thu, 09 Jan 2014 14:43:07 GMT

What I am doing wrong?

我做错了什么?

采纳答案by Deepak Thomas

Solved. Thanks @JasonP for pointers. Changed Server Response Headersfrom

解决了。感谢@JasonP 的指点。更改了服务器响应头

Access-Control-Allow-Headers:*

访问控制允许标题:*

to specific ones

到特定的

Access-Control-Allow-Headers: Content-Type, Accept, X-Requested-With, Session

Access-Control-Allow-Headers: Content-Type, Accept, X-Requested-With, Session

and now it works!

现在它起作用了!