CORS 远程请求

不同域的远程访问之前是用jsonp,但是只能支持get请求,而且写法也很恶心。现在HTML5都来了,应该优先用CORS
前端请求代码

function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// 此时即支持CORS的情况
// 检查XMLHttpRequest对象是否有“withCredentials”属性
// “withCredentials”仅存在于XMLHTTPRequest2对象里
xhr.withCredentials = true;
xhr.open(method, url, true);
// xhr.setRequestHeader('Content-Type', 'application/json');
//xhr.onreadystatechange = handler;
} else if ( typeof XDomainRequest != "undefined") {
console.log("ie support");
// 否则检查是否支持XDomainRequest,IE8和IE9支持
// XDomainRequest仅存在于IE中,是IE用于支持CORS请求的方式
xhr = new XDomainRequest();
xhr.open(method, url);

} else {
// 否则,浏览器不支持CORS
xhr = null;
}
return xhr;
}

var request_url = "http://xxx?apiVersion=2&appID=64&filter=NM&pageSize=&page=&scale=2";
var xhr = createCORSRequest('GET', request_url);
if (!xhr) {
throw new Error('CORS not supported');
}
xhr.send();


服务器端配置。首先apache要安装headers模块。
执行 a2enmod header
然后重启apache 检查是否安装,要进入phpinfo查看 load modules中有无mod_headers

然后在网站的htaccess中添加以下配置

<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "http://xxxx"
Header set Access-Control-Allow-Credentials true
</IfModule>


请注意,如果server中返回结果又做了header跳转,这种跳转请求是不被CORS允许的。会报错。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值