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

24,891

Solved. Thanks @JasonP for pointers. Changed Server Response Headers from

Access-Control-Allow-Headers:*

to specific ones

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

and now it works!

Share:
24,891

Related videos on Youtube

Deepak Thomas
Author by

Deepak Thomas

Apparently, this user prefers to keep an air of mystery about them. Not.

Updated on July 05, 2022

Comments

  • Deepak Thomas
    Deepak Thomas almost 2 years

    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.

      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>");
            }
        });
    

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

    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)

    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?

    • Jason P
      Jason P over 10 years
      You need to use the Access-Control-Allow-Headers response header to specify that the custom headers are allowed.
    • Jason P
      Jason P over 10 years
      I don't think * is a valid value for Access-Control-Allow-Headers. I believe you have to list them. You should be able to get them from the Access-Control-Request-Headers request header though. See developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS.

Related