Skip to content

跨域解决方案

1.JSONP跨域
jsonp的原理就是利用<script>标签没有跨域限制,通过<script>标签src属性,发送带有callback参数的GET请求,服务端将接口返回数据拼凑到callback函数中,返回给浏览器,浏览器解析执行,从而前端拿到callback函数返回的数据
js
<script>
    var script = document.createElement('script');
    script.type = 'text/javascript';

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

    // 回调执行函数
    function handleCallback(res) {
        alert(JSON.stringify(res));
    }
 </script>
2.跨域资源共享(CORS)
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
  • CORS需要浏览器服务器同时支持。目前,所有浏览器都支持该功能,IE浏览器不能低于IE10

  • 在浏览器中,HTTP 请求可以分为简单请求和非简单请求。这两者主要是根据请求的特征和跨域请求的处理方式来区分的。

1.简单请求

简单请求是指符合以下条件的请求:

  • 请求方法:只允许使用以下方法:

GET、HEAD、POST

  • 请求头:请求头只允许包含以下几种: Accept

Accept-Language

Content-Type(仅限于三种值):application/x-www-form-urlencoded、multipart/form-data、text/plain

URL:请求的 URL 必须与当前页面的源(协议、域名、端口)相同

如果请求满足这些条件,它被认为是一个简单请求。简易请求在跨域情况下不会触发 CORS(跨源资源共享)预检请求。

2.非简单请求

非简单请求是指不符合简单请求条件的请求。它们通常具有以下特征:

  • 请求方法:使用了其他 HTTP 方法,例如 PUT、DELETE 等。
  • 请求头:包含了自定义的请求头或不在简单请求允许的范围内的头部。
  • Content-Type:使用了不被允许的 Content-Type,如 application/json。
  • 跨域请求:即使是简单请求,如果跨域,则也会被视为非简单请求

对于非简单请求,浏览器会先发送一个 预检请求(OPTIONS 方法),以确定实际请求是否被允许。这种预检请求会包含一些 CORS 相关的头部,如 Access-Control-Request-MethodAccess-Control-Request-Headers

  • 跨域处理

1.当一个简单请求跨域时,浏览器会自动添加一些 CORS 相关的请求头,例如 Origin,指明请求来源。服务器需要在响应中添加 Access-Control-Allow-Origin 头部,以允许特定来源的请求。示例

请求

text
GET /api/data HTTP/1.1
Origin: https://example.com

响应

text
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://example.com

如果服务器的响应中包含了合适的 Access-Control-Allow-Origin 头,浏览器就会允许请求的结果被访问


2.在非简单请求的情况下,浏览器会首先发送一个 预检请求(OPTIONS 请求),以确认实际请求是否被允许。预检请求会包含以下头部: - Access-Control-Request-Method: 指定实际请求使用的方法 - Access-Control-Request-Headers: 指定实际请求中使用的自定义头部

例如:

  • 预检请求:
text
OPTIONS /api/data HTTP/1.1
Origin: https://example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type

服务器需要对这个预检请求做出响应,返回相应的 CORS 头部:

  • 预检响应:
text
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type

如果预检请求得到了允许的响应,浏览器才会继续发送实际的请求。

3.nginx代理跨域

nginx代理跨域,实质和CORS跨域原理一样,通过配置文件设置请求响应头Access-Control-Allow-Origin...等字段

4.document.domain + iframe跨域

此方案仅限主域相同,子域不同的跨域应用场景。实现原理:两个页面都通过js强制设置document.domain为基础主域,就实现了同域

  • 父窗口:(www.domain.com/a.html)
js
<iframe id="iframe" src="http://child.domain.com/b.html"></iframe>
<script>
    document.domain = 'domain.com';
    var user = 'admin';
</script>
  • 子窗口:(child.domain.com/a.html)
js
<script>
    document.domain = 'domain.com';
    // 获取父窗口中变量
    console.log('get js data from parent ---> ' + window.parent.user);
</script>
5.location.hash + iframe跨域

实现原理: a欲与b跨域相互通信,通过中间页c来实现。 三个页面,不同域之间利用iframe的location.hash传值,相同域之间直接js访问来通信 具体实现:A域:a.html -> B域:b.html -> A域:c.html,a与b不同域只能通过hash值单向通信,b与c也不同域也只能单向通信,但c与a同域,所以c可通过parent.parent访问a页面所有对象

  • a.html:(www.domain1.com/a.html)
js
<iframe id="iframe" src="http://www.domain2.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>
  • b.html:(www.domain2.com/b.html)
js
<iframe id="iframe" src="http://www.domain1.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>
  • c.html:(www.domain1.com/c.html)
js
<script>
    // 监听b.html传来的hash值
    window.onhashchange = function () {
        // 再通过操作同域a.html的js回调,将结果传回
        window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', ''));
    };
</script>
6.window.name + iframe跨域

window.name属性的独特之处:name值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)

  • a.html:(www.domain1.com/a.html)
js
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.domain1.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.domain2.com/b.html', function(data){
    alert(data);
});
  • proxy.html:(www.domain1.com/proxy.html)

中间代理页,与a.html同域,内容为空即可

  • b.html:(www.domain2.com/b.html)
js
<script>
    window.name = 'This is domain2 data!';
</script>
7.postMessage跨域

postMessage是为数不多可以跨域操作的window属性之一 postMessage(data,origin)方法接受两个参数:

  • data: html5规范支持任意基本类型或可复制的对象,但部分浏览器只支持字符串,所以传参时最好用JSON.stringify()序列化。
  • origin: 协议+主机+端口号,也可以设置为"*",表示可以传递给任意窗口,如果要指定和当前窗口同源的话设置为"/"。

示例:

  • a.html:(www.domain1.com/a.html)
js
<iframe id="iframe" src="http://www.domain2.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.domain2.com');
    };

    // 接受domain2返回数据
    window.addEventListener('message', function(e) {
        alert('data from domain2 ---> ' + e.data);
    }, false);
</script>
  • b.html:(www.domain2.com/b.html)
js
<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.domain1.com');
        }
    }, false);
</script>
8.WebSocket协议跨域

与传统的 HTTP 请求不同,WebSocket天生支持跨域连接,在建立连接时并不受同源政策的限制。以下是一些关键点:

WebSocket 的跨域特性:

  • 连接建立:

    WebSocket 连接是通过 ws:// 或 wss:// 协议建立的。在连接时,浏览器会发送一个握手请求到服务器,服务器可以是不同的域名、端口或协议。

  • 同源政策:

    WebSocket 不受同源政策的限制,这意味着你可以从一个域的网页连接到另一个域的 WebSocket 服务器。

  • 服务器配置:

    尽管 WebSocket 允许跨域连接,但服务器需要正确配置以处理连接请求。通常,服务器会在握手响应中返回一些信息,以确保连接的安全性。

  • 安全性:

    使用 wss:// 进行加密连接时,确保服务器的 SSL/TLS 配置正确,以防止中间人攻击。

示例:

服务端:

js
// server.js
const WebSocket = require('ws');

const server = new WebSocket.Server({ port: 8080 });

server.on('connection', (socket) => {
    console.log('Client connected');

    socket.on('message', (message) => {
        console.log(`Received: ${message}`);
        // Echo the message back to the client
        socket.send(`Server: ${message}`);
    });

    socket.on('close', () => {
        console.log('Client disconnected');
    });
});

console.log('WebSocket server is running on ws://localhost:8080');

客户端

html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Demo</title>
</head>
<body>
    <h1>WebSocket Demo</h1>
    <input type="text" id="messageInput" placeholder="Type a message..." />
    <button id="sendButton">Send</button>
    <div id="messages"></div>

    <script>
        const socket = new WebSocket('ws://localhost:8080');

        socket.onopen = () => {
            console.log('Connected to server');
        };

        socket.onmessage = (event) => {
            const messagesDiv = document.getElementById('messages');
            messagesDiv.innerHTML += `<p>${event.data}</p>`;
        };

        socket.onclose = () => {
            console.log('Disconnected from server');
        };
        document.getElementById('sendButton').onclick = () => {
            const input = document.getElementById('messageInput');
            const message = input.value;
            socket.send(message);
            input.value = ''; // Clear input field
        };

    </script>
</body>
</html>