跨域是什么?细说跨域解决办法

一.何为跨域?

跨域是指一个域下的脚本请求另一个域下的资源.这是由浏览器的同源策略(Same origin policy)造成的,是浏览器保护用户的一种安全限制.
同源:指协议、域名、端口号均相同.如果其中一个不同,则属于跨域.

二.同源策略限制三种行为

1.Cookie、LocalStorage 和IndexDB无法读取.
2.DOM和js对象无法获取.
3.AJAX请求不能发送.

三.常见跨域的情况

URL 说明 是否允许通信 是否跨域
http://www.baidu.com/a.js
http://www.baidu.com/js/b.js
协议、域名、端口号均相同,文件路径不同 允许
http://www.baidu.com/a.js
https://www.baidu.com/b.js
协议不同、域名相同、端口号相同 不允许
http://www.baidu.com/a.js
http://www.taobao.com/js/b.js
协议相同、域名不同、端口号相同 不允许
http://www.baidu.co:8080m/a.js
http://www.baidu.com/js/b.js
协议相同、域名相同、端口号不同 不允许
http://www.baidu.com/a.js
http://192.168.4.29/js/b.js
域名和域名对应的ip 不允许
http://www.baidu.com/a.js
http://x.baidu.com/b.js
主域相同,子域不同 不允许

四.跨域解决方案

1.通过jsonp
2.document.domain + iframe跨域
3.location.hash + iframe
4.window.name+iframe跨域
5.postMessage跨域
6.跨域资源共享(CORS)
7.nginx代理跨域
8.nodejs中间件代理跨域
9.WebSocket协议跨域

(一).通过jsonp跨域

原理:通常发生跨域是由于发送ajax请求造成的,因此可以通过动态创建一个script,向目标网址发送跨域请求.

原生

 <script>
    var script = document.createElement('script');
    script.type = 'text/javascript';

    // 传参一个回调函数名给后端,方便后端返回时执行这个在前端定义的回调函数
    script.src = 'http://www.baidu.com:8080/login?user=admin&callback=handleCallback';
    document.head.appendChild(script);

    // 回调执行函数
    function handleCallback(res) {
    
    
        alert(JSON.stringify(res));
    }
 </script>

服务端返回全局函数

handleCallback({
    
    "status": true, "user": "admin"})

jquery ajax

$.ajax({
    
    
    url: 'http://www.baidu2.com:8080/login',
    type: 'get',
    dataType: 'jsonp',  // 请求方式为jsonp
    jsonpCallback: "handleCallback",    // 自定义回调函数名
    data: {
    
    }
});

vue.js

this.$http.jsonp('http://www.baidu2.com:8080/login', {
    
    
    params: {
    
    },
    jsonp: 'handleCallback'
}).then((res) => {
    
    
    console.log(res); 
})

后端node.js代码示例

var querystring = require('querystring');
var http = require('http');
var server = http.createServer();

server.on('request', function(req, res) {
    
    
    var params = qs.parse(req.url.split('?')[1]);
    var fn = params.callback;

    // jsonp返回设置
    res.writeHead(200, {
    
     'Content-Type': 'text/javascript' });
    res.write(fn + '(' + JSON.stringify(params) + ')');

    res.end();
});

server.listen('8080');
console.log('Server is running at port 8080...');

缺点:jsonp只能实现get一个请求.

(二).document.domain + iframe跨域(仅限主域相同,子域不同)

原理:两个页面强制设置document.domain为基础主域,实现同域.
1.父窗口(http://www.baidu.com/a.html)

<iframe id="iframe" src="http://child.domain.com/b.html"></iframe>
<script>
    document.domain = 'domain.com';
    var user = 'admin';
</script>

2.子窗口(http://child.baidu.com/b.html)

<script>
    document.domain = 'domain.com';
    // 获取父窗口中变量
    alert('get js data from parent ---> ' + window.parent.user);
</script>

(三).location.hash + iframe

原理:a和b页面跨域相互通信,通过中间页c来实现,a和c同域.三个页面,不同域之间利用iframe的location.hash传值,相同域直接js来通信.
1.a.html(http://www.baidu1.com/a.html)

<iframe id="iframe" src="http://www.baidu2.com/b.html" style="display:none;"></iframe>
<script>
    var iframe = document.getElementById('iframe');

    // 向b.html传hash值
    setTimeout(function() {
    
    
        iframe.src = iframe.src + '#user=admin';
    }, 1000);
    
    // 开放给同域c.html的回调方法
    function onCallback(res) {
    
    
        alert('data from c.html ---> ' + res);
    }
</script>

2.b.html(http://www.baidu2.com/b.html)

<iframe id="iframe" src="http://www.baidu1.com/c.html" style="display:none;"></iframe>
<script>
    var iframe = document.getElementById('iframe');

    // 监听a.html传来的hash值,再传给c.html
    window.onhashchange = function () {
    
    
        iframe.src = iframe.src + location.hash;
    };
</script>

3.c.html(http://www.baidu1.com/c.html)

<script>
    // 监听b.html传来的hash值
    window.onhashchange = function () {
    
    
        // 再通过操作同域a.html的js回调,将结果传回
        window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', ''));
    };
</script>

(四).window.name + iframe

原理:window.name在不同的页面(甚至不同域名)加载后依旧存在,并可以支持2MB长的值.
1.a.html(http://www.baidu1.com/a.html)

var proxy = function(url, callback) {
    
    
    var state = 0;
    var iframe = document.createElement('iframe');

    // 加载跨域页面
    iframe.src = url;

    // onload事件会触发2次,第1次加载跨域页,并留存数据于window.name
    iframe.onload = function() {
    
    
        if (state === 1) {
    
    
            // 第2次onload(同域proxy页)成功后,读取同域window.name中数据
            callback(iframe.contentWindow.name);
            destoryFrame();

        } else if (state === 0) {
    
    
            // 第1次onload(跨域页)成功后,切换到同域代理页面
            iframe.contentWindow.location = 'http://www.baidu1.com/proxy.html';
            state = 1;
        }
    };

    document.body.appendChild(iframe);

    // 获取数据以后销毁这个iframe,释放内存;这也保证了安全(不被其他域frame js访问)
    function destoryFrame() {
    
    
        iframe.contentWindow.document.write('');
        iframe.contentWindow.close();
        document.body.removeChild(iframe);
    }
};

// 请求跨域b页面数据
proxy('http://www.baidu2.com/b.html', function(data){
    
    
    alert(data);
});

2.proxy.html(http://www.baidu1.com/proxy.html)
中间页,内容为空即可.
3.c.html(http://www.baidu2.com.c.html)

<script>
    window.name = 'This is domain2 data!';
</script>

(五).postMessage

postMessage是HTML5 XMLHttpRequest Level2 中的API,是为数不多可以支持跨域操作的window属性之一.

1.a.html(http://www.baidu1.com/a.html)

<iframe id="iframe" src="http://www.baidu2.com/b.html" style="display:none;"></iframe>
<script>       
    var iframe = document.getElementById('iframe');
    iframe.onload = function() {
    
    
        var data = {
    
    
            name: 'aym'
        };
        // 向domain2传送跨域数据
        iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.baidu2.com');
    };

    // 接受domain2返回数据
    window.addEventListener('message', function(e) {
    
    
        alert('data from domain2 ---> ' + e.data);
    }, false);
</script>

2.b.html(http://www.baidu2.com/b.html)

<script>
    // 接收domain1的数据
    window.addEventListener('message', function(e) {
    
    
        alert('data from domain1 ---> ' + e.data);

        var data = JSON.parse(e.data);
        if (data) {
    
    
            data.number = 16;

            // 处理后再发回domain1
            window.parent.postMessage(JSON.stringify(data), 'http://www.baidu1.com');
        }
    }, false);
</script>

(六).跨域资源共享(CORS)

普通跨域请求:只服务端设置Access-Control-Allow-Origin即可,前端无须设置,若要带cookie请求:前后端都需要设置。

需注意的是:由于同源策略的限制,所读取的cookie为跨域请求接口所在域的cookie,而非当前页。如果想实现当前页cookie的写入,可参考下文:七、nginx反向代理中设置proxy_cookie_domain 和 八、NodeJs中间件代理中cookieDomainRewrite参数的设置。

目前,所有浏览器都支持该功能(IE8+:IE8/9需要使用XDomainRequest对象来支持CORS)),CORS也已经成为主流的跨域解决方案。

前端
1.原生

var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容

// 前端设置是否带cookie
xhr.withCredentials = true;

xhr.open('post', 'http://www.baidu2.com:8080/login', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=admin');

xhr.onreadystatechange = function() {
    
    
    if (xhr.readyState == 4 && xhr.status == 200) {
    
    
        alert(xhr.responseText);
    }
};

2.jquery

$.ajax({
    
    
    ...
   xhrFields: {
    
    
       withCredentials: true    // 前端设置是否带cookie
   },
   crossDomain: true,   // 会让请求头中包含跨域的额外信息,但不会含cookie
    ...
});

3.vue
axios设置

axios.defaults.withCredentials = true

vue-resource设置

Vue.http.options.credentials = true

服务端
1.java后台

/*
 * 导入包:import javax.servlet.http.HttpServletResponse;
 * 接口参数中定义:HttpServletResponse response
 */

// 允许跨域访问的域名:若有端口需写全(协议+域名+端口),若没有端口末尾不用加'/'
response.setHeader("Access-Control-Allow-Origin", "http://www.baidu1.com"); 

// 允许前端带认证cookie:启用此项后,上面的域名不能为'*',必须指定具体的域名,否则浏览器会提示
response.setHeader("Access-Control-Allow-Credentials", "true"); 

// 提示OPTIONS预检时,后端需要设置的两个常用自定义头
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");

2.Nodejs

var http = require('http');
var server = http.createServer();
var qs = require('querystring');

server.on('request', function(req, res) {
    
    
    var postData = '';

    // 数据块接收中
    req.addListener('data', function(chunk) {
    
    
        postData += chunk;
    });

    // 数据接收完毕
    req.addListener('end', function() {
    
    
        postData = qs.parse(postData);

        // 跨域后台设置
        res.writeHead(200, {
    
    
            'Access-Control-Allow-Credentials': 'true',     // 后端允许发送Cookie
            'Access-Control-Allow-Origin': 'http://www.baidu1.com',    // 允许访问的域(协议+域名+端口)
            /* 
             * 此处设置的cookie还是domain2的而非domain1,因为后端也不能跨域写cookie(nginx反向代理可以实现),
             * 但只要domain2中写入一次cookie认证,后面的跨域接口都能从domain2中获取cookie,从而实现所有的接口都能跨域访问
             */
            'Set-Cookie': 'l=a123456;Path=/;Domain=www.baidu2.com;HttpOnly'  // HttpOnly的作用是让js无法读取cookie
        });

        res.write(JSON.stringify(postData));
        res.end();
    });
});

server.listen('8080');
console.log('Server is running at port 8080...');

(七).nginx代理跨域

1.nginx配置解决iconfont
浏览器跨域访问js、css、img等常规静态资源被同源策略许可,但iconfont字体文件(eot|otf|ttf|woff|svg)例外,此时可在nginx的静态资源服务器中加入以下配置。

location / {
    
    
  add_header Access-Control-Allow-Origin *;
}

2.nginx反向代理接口
nginx具体配置

#proxy服务器
server {
    
    
    listen       81;
    server_name  www.baidu1.com;

    location / {
    
    
        proxy_pass   http://www.baidu2.com:8080;  #反向代理
        proxy_cookie_domain www.baidu2.com www.domain1.com; #修改cookie里域名
        index  index.html index.htm;

        # 当用webpack-dev-server等中间件代理接口访问nignx时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不启用
        add_header Access-Control-Allow-Origin http://www.baidu1.com;  #当前端只跨域不带cookie时,可为*
        add_header Access-Control-Allow-Credentials true;
    }
}

1.前端示例

var xhr = new XMLHttpRequest();

// 前端开关:浏览器是否读写cookie
xhr.withCredentials = true;

// 访问nginx中的代理服务器
xhr.open('get', 'http://www.baidu1.com:81/?user=admin', true);
xhr.send();

2.Node.js示例

var http = require('http');
var server = http.createServer();
var qs = require('querystring');

server.on('request', function(req, res) {
    
    
    var params = qs.parse(req.url.substring(2));

    // 向前台写cookie
    res.writeHead(200, {
    
    
        'Set-Cookie': 'l=a123456;Path=/;Domain=www.baidu2.com;HttpOnly'   // HttpOnly:脚本无法读取
    });

    res.write(JSON.stringify(params));
    res.end();
});

server.listen('8080');
console.log('Server is running at port 8080...');

(八).Node.js中间件代理

原理:通过代理服务器接收数据并转发数据.
1.非vue框架的跨域(2次)
前端

#proxy服务器
server {
    
    
    listen       81;
    server_name  www.baidu1.com;

    location / {
    
    
        proxy_pass   http://www.baidu2.com:8080;  #反向代理
        proxy_cookie_domain www.baidu2.com www.domain1.com; #修改cookie里域名
        index  index.html index.htm;

        # 当用webpack-dev-server等中间件代理接口访问nignx时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不启用
        add_header Access-Control-Allow-Origin http://www.domain1.com;  #当前端只跨域不带cookie时,可为*
        add_header Access-Control-Allow-Credentials true;
    }
}

Node.js后台

var express = require('express');
var proxy = require('http-proxy-middleware');
var app = express();

app.use('/', proxy({
    
    
    // 代理跨域目标接口
    target: 'http://www.baidu2.com:8080',
    changeOrigin: true,

    // 修改响应头信息,实现跨域并允许带cookie
    onProxyRes: function(proxyRes, req, res) {
    
    
        res.header('Access-Control-Allow-Origin', 'http://www.domain1.com');
        res.header('Access-Control-Allow-Credentials', 'true');
    },

    // 修改响应信息中的cookie域名
    cookieDomainRewrite: 'www.baidu1.com'  // 可以为false,表示不修改
}));

app.listen(3000);
console.log('Proxy server is listen at port 3000...');

2.vue框架的跨域(1次跨域)

module.exports = {
    
    
    entry: {
    
    },
    module: {
    
    },
    ...
    devServer: {
    
    
        historyApiFallback: true,
        proxy: [{
    
    
            context: '/login',
            target: 'http://www.baidu2.com:8080',  // 代理跨域目标接口
            changeOrigin: true,
            secure: false,  // 当代理某些https服务报错时用
            cookieDomainRewrite: 'www.baidu1.com'  // 可以为false,表示不修改
        }],
        noInfo: true
    }
}

(九).WebSocket协议跨域

WebSocket protocol是HTML5一种新的协议。它实现了浏览器与服务器全双工通信,同时允许跨域通讯,是server push技术的一种很好的实现。
原生WebSocket API使用起来不太方便,我们使用Socket.io,它很好地封装了webSocket接口,提供了更简单、灵活的接口,也对不支持webSocket的浏览器提供了向下兼容。
1.前端

<div>user input:<input type="text"></div>
<script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
<script>
var socket = io('http://www.baidu2.com:8080');

// 连接成功处理
socket.on('connect', function() {
    
    
    // 监听服务端消息
    socket.on('message', function(msg) {
    
    
        console.log('data from server: ---> ' + msg); 
    });

    // 监听服务端关闭
    socket.on('disconnect', function() {
    
     
        console.log('Server socket has closed.'); 
    });
});

document.getElementsByTagName('input')[0].onblur = function() {
    
    
    socket.send(this.value);
};
</script>

2.Nodejs socket后台

<div>user input:<input type="text"></div>
<script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
<script>
var socket = io('http://www.domain2.com:8080');

// 连接成功处理
socket.on('connect', function() {
    
    
    // 监听服务端消息
    socket.on('message', function(msg) {
    
    
        console.log('data from server: ---> ' + msg); 
    });

    // 监听服务端关闭
    socket.on('disconnect', function() {
    
     
        console.log('Server socket has closed.'); 
    });
});

document.getElementsByTagName('input')[0].onblur = function() {
    
    
    socket.send(this.value);
};
</script>

文章部分内容参考:https://segmentfault.com/a/1190000011145364

猜你喜欢

转载自blog.csdn.net/qq_38870665/article/details/108816778