JavaScript CORS实现跨域

来源:互联网 发布:万和热水器怎么样 知乎 编辑:程序博客网 时间:2024/04/30 12:36

在JavaScript中,通过ajax向后台发送请求,其受限于同源策略。同源策略规定跨域之间的脚本是隔离的,一个域的脚本不能访问和操作另外一个域的绝大部分属性和方法。同源即意味着两个域具有相同的协议(如http), 相同的端口(如8080),相同的host(如www.baidu.com)。

CORS(Cross-Origin Resource Sharing, 跨域资源共享)是一种很好的解决js跨域的技术。CORS 背后的基本思想,就是使用自定义的HTTP 头部让浏览器与服务器进行沟通,从而决定请求或响应是应该成功,还是应该失败。

在IE8 中引入了XDR(XDomainRequest)类型。这个对象与XHR 类似,但能实现安全可靠的跨域通信。

var xdr = new XDomainRequest();xdr.onload = function(){    alert(xdr.responseText);};xdr.open("get", "http://localhost:8080/DomainDemo/DomainServlet");xdr.send(null);

在xdr中,所有的请求都是异步的,所以open函数只接受两个函数。在接收到响应后,你只能访问响应的原始文(responseText);没有办法确定响应的状态代码。而且,只要响应有效就会触发load 事件,如果失败(包括响应中缺少Access-Control-Allow-Origin 头部)就会触发error 事件。

对于其他浏览器(Chrome, Firefox...),它们都是通过XMLHttpRequest对象实现对CORS的支持,如果要请求另一个域中的资源,只要在open方法的url参数中填入绝对的URL即可。

var xhr = new getXMLHttpRequest();xhr.onreadystatechange = function(){    if(xhr.readyState === 4 && xhr.status === 200) {        console.log(xhr.responseText);    }};xhr.open("get", "http://localhost:8080/DomainDemo/DomainServlet", true);xhr.send();

下面是跨浏览器实现CORS的代码

function getRequest(method, url) {    var xhr = new XMLHttpRequest();    if("withCredentials" in xhr) {        // For Chrome, Firefox ...        xhr.open(method, url, true);    } else if (typeof XDomainRequest != 'undefined') {        // For IE8+        xhr = new XDomainRequest();        xhr.open(method, url);    } else {        throw new Error('The browser don\'t support CORS');    }    return xhr;}function showName() {    var xhr = getRequest('GET', 'http://localhost:8080/DomainDemo/DomainServlet');    if(xhr) {        xhr.onload = function() {            alert(xhr.responseText);        };        xhr.onerror = function() {            alert('Error occur');        };        xhr.send();    }}

如果直接使用上面的代码进行跨域请求,则浏览器会报错:

XMLHttpRequest cannot loadhttp://localhost:8080/DomainDemo/DomainServlet. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.lk.com:8090' is therefore not allowed access.


在服务器端,我们可以通过设置Access-Control-Allow-Origin来实现对于CORS的支持。如果浏览器检测到相应的设置,就可以允许Ajax进行跨域的访问。

DomainDemo中的DomainServlet.java

</pre><pre style="font-family: 宋体; font-size: 7.2pt; background-color: rgb(255, 255, 255);"><pre name="code" class="java">protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    // 允许跨域访问的domain    response.setHeader("Access-Control-Allow-Origin", "http://www.lk.com:8090");    // 允许请求头中带有的请求头,不配置的话不能访问    response.setHeader("Access-Control-Allow-Headers", "origin, x-requested-with, content-type, accept, x-apikey, x-authstring");    // 允许跨域的请求类型    response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");    response.setContentType("text/html;charset=utf-8");    PrintWriter out = response.getWriter();    out.print("Kurtis");    out.flush();    out.close();}

如果将Access-Control-Allow-Origin设置为"*",则允许所用请求访问这个URL。


0 0
原创粉丝点击