php跨域请求ajax用Authorization上传token报错 “Access to XMLHttpRequest at 'http://adminapi.shop.com/logout' from origin 'http://www.adminshop.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.”,怎么解决
1.php代码
header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
header('Access-Control-Allow-Methods:POST,GET,PUT,OPTIONS,DELETE,PATCH'); // 允许请求的类型
header('Access-Control-Allow-Headers:Origin,X-Requested-With,X_Requested_With,X-PINGOTHER,Content-Type,Authorization,lpy');
2.JS代码
$.ajax({
url: 'http://adminapi.shop.com/logout',
type: 'get',
//headers: {'Authorization': token},
beforeSend: function (XHR) {
console.log(token)
XHR.setRequestHeader("Authorization",token);
},
success:function(r,textStatus,xhr){
var res=JSON.parse(r);
console.log(res)
}
});
beforeSend: function (XHR) {
console.log(token)
XHR.setRequestHeader("Authorization",token);
}
或
headers: {'Authorization': token}
时没问题
这个是跨域,提示很清楚,在请求头配置允许跨域即可,这个是浏览器的同源策略