Cross domain POST request is not sending cookie Ajax Jquery

Kirill Reva picture Kirill Reva · Jan 22, 2013 · Viewed 101.9k times · Source

Seems that something similar already has been discussed on stackoverflow, but i could not find exactly the same.

I am trying to send Cookie with CORS(Cross-origin resource sharing), but it is not working.

This is my code.

$.ajax(
    { 
      type: "POST",
      url: "http://example.com/api/getlist.json",
      dataType: 'json',
      xhrFields: {
           withCredentials: true
      },
      crossDomain: true,
      beforeSend: function(xhr) {
            xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
      },
      success: function(){
           alert('success');
      },
      error: function (xhr) {
             alert(xhr.responseText);
      }
    }
);

I dont see this cookie in request HEADER.

Answer

monsur picture monsur · Jan 23, 2013

You cannot set or read cookies on CORS requests through JavaScript. Although CORS allows cross-origin requests, the cookies are still subject to the browser's same-origin policy, which means only pages from the same origin can read/write the cookie. withCredentials only means that any cookies set by the remote host are sent to that remote host. You will have to set the cookie from the remote server by using the Set-Cookie header.