简体   繁体   中英

How to send a cross-domain ajax request with cookies

I'm developing a SaaS application, users create account and login in my SaaS system. Then, the SaaS application has a JS code that customers should include this JS code in their websites, and inside the code I need to send a POST Ajax Request to my SaaS domain (it's a cross-domain request).

The problem is that in order to share the credential of logged-in users, I have to set withCredentials property and Access-Control-Allow-Credentials header to true .

I'm not sure whether this is a good approach or not? Maybe I should use another approach like using OAuth or something to share the logged-in users credential...

I will appreciate any advices.

You need to be using JSONP as your type:

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

To enable cross domain requests with credentials, your server should support CORS . With CORS enabled your client code can add the withCredentials set to true to include cookies in the requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM