跨域解决方案CORS使用方法

时间:2023-11-23 09:11:20

CORS(Cross-Origin Resource Sharing), 目前CORS还处于w3c的草案,它定义了跨域访问时服务器和客户端之间如何通信。他的原理是通过定义HTTP头部的信息,来让客户端和服务器互相确认,从而决定是否相应本次请求。

兼容性: IE10+  chrome21+  firefox21+  safari5.1+  opera12.1+ (IE8, 9中使用XDomainRequest)

    详见 http://caniuse.com/cors , 可通过(new XMLHttpRequest).withCredentials !== undefined判断

客户端:

 function compatibleCORS(method, url) {
var xhr = new XMLHttpRequest();
if (xhr.withCredentials !== undefined) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest !== "undefined") {
//XDomainRequest是IE用于支持CORS请求的对象
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
} var xhr = compatibleCORS('GET', "your url");
if (!xhr) {
throw new Erorr("CORS不被支持");
}

服务端:

  通过设置http响应头Access-Control-Allow-Origin: www.xxx.com(这里可以是*, 代表接受任意域名的跨域申请, 但为了安全策略, 一般情况下不要这样做)

  这样客户端的代码就能得到响应