HTML5如何实现跨域

74 阅读3分钟

HTML5如何实现跨域

在 HTML5 中,跨域(Cross-Origin)是指浏览器允许一个域下的网页向另一个域发送请求。由于浏览器的同源策略(Same-Origin Policy),默认情况下,跨域请求是被禁止的。HTML5 提供了多种方式来实现跨域请求,以下是常用的跨域解决方案:

1. CORS(跨域资源共享)

CORS(Cross-Origin Resource Sharing)是 W3C 标准,允许服务器明确指定哪些域可以访问其资源。

实现方式

  1. 服务器端配置

    • 在服务器响应头中添加 Access-Control-Allow-Origin,指定允许访问的域。

    • 示例:

      Access-Control-Allow-Origin: https://example.com
      

      或者允许所有域:

      Access-Control-Allow-Origin: *
      
  2. 客户端请求

    • 使用 XMLHttpRequestFetch API 发送跨域请求。
    • 示例:
      fetch('https://api.example.com/data', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error(error));
      

适用场景

  • 需要从不同域获取资源的场景。
  • 支持现代浏览器。

2. JSONP(JSON with Padding)

JSONP 是一种利用 <script> 标签不受同源策略限制的特性来实现跨域请求的方法。

实现方式

  1. 服务器端

    • 返回一个 JavaScript 函数调用,函数名由客户端指定。
    • 示例:
      callbackFunction({ "name": "Alice", "age": 25 });
      
  2. 客户端

    • 动态创建 <script> 标签,指定回调函数。
    • 示例:
      function callbackFunction(data) {
        console.log(data);
      }
      
      const script = document.createElement('script');
      script.src = 'https://api.example.com/data?callback=callbackFunction';
      document.body.appendChild(script);
      

适用场景

  • 仅支持 GET 请求。
  • 适用于旧版浏览器(如 IE8)。

3. 代理服务器

通过服务器端代理实现跨域请求,客户端请求同域下的代理服务器,代理服务器转发请求到目标服务器。

实现方式

  1. 服务器端

    • 在同域下设置代理服务器,接收客户端请求并转发到目标服务器。
    • 示例(Node.js):
      const http = require('http');
      const request = require('request');
      
      http.createServer((req, res) => {
        const url = 'https://api.example.com/data';
        req.pipe(request(url)).pipe(res);
      }).listen(3000);
      
  2. 客户端

    • 向代理服务器发送请求。
    • 示例:
      fetch('http://localhost:3000/data')
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error(error));
      

适用场景

  • 适用于所有浏览器。
  • 需要服务器端支持。

4. WebSocket

WebSocket 是一种双向通信协议,不受同源策略限制,可以实现跨域通信。

实现方式

  1. 服务器端

    • 创建 WebSocket 服务器。
    • 示例(Node.js + ws 库):
      const WebSocket = require('ws');
      const wss = new WebSocket.Server({ port: 8080 });
      
      wss.on('connection', function connection(ws) {
        ws.on('message', function incoming(message) {
          console.log('收到消息:', message);
        });
        ws.send('Hello, Client!');
      });
      
  2. 客户端

    • 创建 WebSocket 连接。
    • 示例:
      const socket = new WebSocket('ws://example.com:8080');
      
      socket.onopen = function() {
        console.log('连接已打开');
        socket.send('Hello, Server!');
      };
      
      socket.onmessage = function(event) {
        console.log('收到消息:', event.data);
      };
      

适用场景

  • 实时通信场景(如聊天室、实时数据更新)。

5. postMessage

postMessage 是 HTML5 提供的一种跨文档通信机制,可以在不同域的窗口或 iframe 之间传递消息。

实现方式

  1. 发送消息

    • 使用 postMessage 发送消息。
    • 示例:
      const targetWindow = window.open('https://example.com');
      targetWindow.postMessage('Hello, Example!', 'https://example.com');
      
  2. 接收消息

    • 监听 message 事件。
    • 示例:
      window.addEventListener('message', function(event) {
        if (event.origin !== 'https://example.com') return;
        console.log('收到消息:', event.data);
      });
      

适用场景

  • 跨域窗口或 iframe 之间的通信。

总结

方法适用场景优点缺点
CORS现代浏览器,支持多种请求类型标准方式,支持复杂请求需要服务器支持
JSONP旧版浏览器,仅支持 GET 请求简单易用仅支持 GET,安全性较低
代理服务器所有浏览器,支持多种请求类型无需客户端修改需要服务器支持
WebSocket实时通信场景双向通信,实时性高需要服务器支持
postMessage跨域窗口或 iframe 通信安全,支持复杂数据仅适用于窗口或 iframe 通信

通过合理选择跨域解决方案,可以满足不同场景下的需求,同时确保应用的安全性和性能。

更多vue相关插件及后台管理模板可访问vue admin reference,代码详情请访问github