简体   繁体   English

如何发送带有Cookie的跨域Ajax请求

[英]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. 我正在开发SaaS应用程序,用户创建帐户并登录我的SaaS系统。 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). 然后,SaaS应用程序具有一个JS代码,客户应将此JS代码包括在他们的网站中,并且在代码内部,我需要向我的SaaS域发送一个POST Ajax请求(这是一个跨域请求)。

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 . 问题是,为了共享登录用户的凭据,我必须将withCredentials属性和Access-Control-Allow-Credentials标头设置为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... 也许我应该使用其他方法,例如使用OAuth或其他方法来共享已登录用户的凭据...

I will appreciate any advices. 我将不胜感激任何建议。

You need to be using JSONP as your type: 您需要使用JSONP作为您的类型:

$.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 . 要使用凭据启用跨域请求,您的服务器应支持CORS With CORS enabled your client code can add the withCredentials set to true to include cookies in the requests. 启用CORS后,您的客户代码可以将withCredentials设置为true以在请求中包含cookie。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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