AJAX 跨域请求 cookie问题
文章目录
js跨域请求的时候遇到的问题.
接口允许跨域
这个比较简单,只需要在接口上添加输出头即可.
Access-Control-Allow-Origin 是开放的域名,我图省事就是是* 通配符了.
access-control-allow-credentials
true
access-control-allow-headers
Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With
access-control-allow-methods
GET, POST, PATCH, PUT, DELETE, OPTIONS
access-control-allow-origin
*
access-control-max-age
1800
JS部分
如果JS不作任何设置,调用接口是没问题的.
但是api需要传递cookie的时候,不设置是无法使用的.
如果调用接口需要传递cookie,只需要在请求前添加一句.
$.ajaxSetup({crossDomain: true, xhrFields: {withCredentials: true}});
//然后再调用
//$.ajax();
//$.post();
//$.get();
//$.getJSON():
方法二
ajax内部添加
$.ajax({
url: 'URL',
type: 'DELETE',
crossDomain: true,
xhrFields: {withCredentials: true},
success: function(result) {
//....
}
});
原生XHR请求
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://xxxx.com/", true);
xhr.withCredentials = true; //支持跨域发送cookies
xhr.send();
参考
https://blog.csdn.net/hfahe/article/details/7730944