跨域通信是指在不同域名、端口或协议的窗口之间进行数据传递

70 阅读1分钟

跨域通信是指在不同域名、端口或协议的窗口之间进行数据传递。 以下是一些常用的跨域通信方法:

  1. CORS(跨域资源共享):CORS 是一种 W3C 标准,允许服务器在响应头中设置 Access-Control-Allow-Origin 等字段,从而允许浏览器跨域访问资源。
// 服务器端设置响应头
response.setHeader('Access-Control-Allow-Origin', '*');
  1. JSONP(JSON with Padding):JSONP 是一种通过动态创建 <script> 标签并设置其 src 属性来实现跨域请求的方法。服务器端返回一个包含回调函数的 JSON 数据,浏览器端执行该回调函数并处理数据。
// 客户端
function handleData(data) {
  console.log(data);
}

const script = document.createElement('script');
script.src = 'http://example.com/data?callback=handleData';
document.body.appendChild(script);

// 服务器端
const data = { key: 'value' };
const callback = 'handleData';
response.end(`${callback}(${JSON.stringify(data)})`);
  1. postMessagepostMessage 是 HTML5 引入的一种跨域通信方法,允许不同窗口之间发送消息。
// 发送方
window.postMessage('message', 'http://example.com');

// 接收方
window.addEventListener('message', (event) => {
  if (event.origin === 'http://example.com') {
    console.log(event.data);
  }
});
  1. WebSocket:WebSocket 是一种双向通信协议,可以实现跨域通信。
const socket = new WebSocket('ws://example.com/socket');
socket.onmessage = (event) => {
  console.log(event.data);
};
socket.send('message');
  1. iframe + window.name:通过在父窗口和子窗口之间设置 window.name 属性,实现跨域通信。

  2. iframe + location.hash:通过在父窗口和子窗口之间设置 location.hash 属性,实现跨域通信。

  3. iframe + postMessage:结合 iframepostMessage 方法实现跨域通信。

  4. 服务器代理:通过服务器端进行请求转发,实现跨域通信。客户端将请求发送到自己的服务器,然后服务器将请求转发到目标服务器,最后将目标服务器的响应返回给客户端。