Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 432
Deepak Thomas Avatar asked Jan 09 '14 14:01

Deepak Thomas


1 Answers

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!

like image 145
Deepak Thomas Avatar answered Nov 07 '22 08:11

Deepak Thomas