8 cross-domain solutions for the front end

In front-end development, there are 8 common cross-domain solutions:

  1. JSONP (JSON with Padding): Taking advantage of <script>the cross-domain characteristics of tags, by dynamically creating <script>tags, requesting an interface with a callback function, the data returned by the server will be passed in as parameters of the callback function, thereby realizing cross-domain requests.
function jsonp(url, callback) {
    
    
  const script = document.createElement('script');
  script.src = url + '?callback=' + callback;
  document.body.appendChild(script);
}

jsonp('http://api.example.com/data', 'handleResponse');
function handleResponse(data) {
    
    
  console.log(data);
}
  1. CORS (Cross-Origin Resource Sharing): Set the response header through the server to allow cross-domain requests from the specified source (domain name, protocol, port).
// 服务器响应头设置
Access-Control-Allow-Origin: http://example.com
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type

// 前端请求
fetch('http://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));
  1. Reverse proxy: Set up a proxy server on the server side, send the front-end request to the target server, and return the target server's response to the front-end, thereby realizing cross-domain requests.
// 服务器端代理
app.use('/api', proxy({
    
     target: 'http://api.example.com', changeOrigin: true }));

// 前端请求
fetch('/api/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));
  1. WebSocket: Use the WebSocket protocol for cross-domain communication. The WebSocket protocol supports cross-domain requests by default.
const socket = new WebSocket('ws://api.example.com');
socket.onmessage = function(event) {
    
    
  console.log(event.data);
};
  1. postMessage: window.postMessagecross-domain communication between different windows through methods, which can realize cross-domain data transfer and message notification.
// 窗口A发送消息
window.postMessage('Hello', 'http://example.com');

// 窗口B接收消息
window.addEventListener('message', function(event) {
    
    
  if (event.origin === 'http://example.com') {
    
    
    console.log(event.data);
  }
});
  1. WebSocket + CORS: Combine WebSocket and CORS, use WebSocket to establish a cross-domain connection, and then send HTTP requests through CORS.
const socket = new WebSocket('ws://api.example.com');
socket.onopen = function() {
    
    
  socket.send('GET /data HTTP/1.1\r\nHost: api.example.com\r\n\r\n');
};
socket.onmessage = function(event) {
    
    
  console.log(event.data);
};
  1. Nginx reverse proxy: Set up a reverse proxy through the Nginx server to forward the front-end request to the target server to achieve cross-domain requests.
location /api {
  proxy_pass http://api.example.com;
}
  1. WebRTC: Using WebRTC technology for cross-domain communication, point-to-point audio and video transmission and data transmission can be achieved.

scenes to be used:

  1. JSONP:

    • Advantages: Good compatibility, supports old version browsers; simple and easy to use, no special configuration is required.
    • Disadvantages: Only supports GET requests; has security risks and is vulnerable to XSS attacks; can only send data in JSON format.
    • Usage scenario: Suitable for simple cross-domain requests and low security requirements.
  2. CORS:

    • Advantages: Supports all types of HTTP requests; high security and can be controlled by setting request headers; no special front-end code is required.
    • Disadvantages: The server needs to set the response header, which cannot be used in some cases where there is no permission to modify the response header.
    • Usage scenarios: Suitable for situations where complex cross-domain requests are required and have high security requirements.
  3. Reverse proxy:

    • Advantages: Applicable to all types of HTTP requests; no special front-end code required; request processing and filtering can be performed on the server side.
    • Disadvantages: A proxy server needs to be set up on the server side, which increases the burden and complexity of the server.
    • Usage scenarios: Suitable for situations where request processing or filtering needs to be performed on the server side, or where the response header cannot be modified.
  4. WebSocket:

    • Advantages: Supports real-time communication and allows two-way communication; fewer cross-domain restrictions.
    • Disadvantages: The server needs to support the WebSocket protocol; not suitable for transmitting large amounts of data.
    • Usage scenarios: Suitable for real-time communication or scenarios requiring two-way communication, such as chat rooms, real-time data monitoring, etc.
  5. postMessage:

    • Advantages: Simple and easy to use, no special configuration required; supports cross-window communication.
    • Disadvantages: Can only perform point-to-point communication and cannot broadcast messages; security verification is required at the receiving end.
    • Usage scenarios: Suitable for communication between different windows, such as parent-child windows, cross-domain iframes, etc.
  6. WebSocket + CORS:

    • Advantages: It combines the advantages of WebSocket and CORS to support real-time communication and complex cross-domain requests.
    • Disadvantages: The server needs to support both WebSocket and CORS.
    • Usage scenarios: Suitable for situations requiring real-time communication and complex cross-domain requests.
  7. Nginx reverse proxy:

    • Advantages: Supports all types of HTTP requests; request processing and filtering can be performed on the Nginx server.
    • Disadvantages: Nginx server needs to be configured on the server side, which increases the burden and complexity of the server.
    • Usage scenarios: Suitable for situations where request processing or filtering needs to be performed on the server side, or where the response header cannot be modified.
  8. WebRTC:

    • Advantages: Supports point-to-point audio and video transmission and data transmission; fewer cross-domain restrictions.
    • Disadvantages: The browser and server need to support the WebRTC protocol at the same time; configuration and use are complicated.
    • Usage scenarios: Suitable for scenarios that require real-time audio and video transmission or data transmission, such as video conferencing, real-time games, etc.

Guess you like

Origin blog.csdn.net/ACCPluzhiqi/article/details/132767558