Solve Axios cross-domain issues and easily implement interface calls

Cross-domain refers to accessing resources in another domain. Due to the browser's same-origin policy, cross-domain requests are not allowed by default when using XMLHttpRequest and Fetch requests. The root cause of cross-origin is the browser's Same Origin Policy, which is a security restriction imposed by the browser on JavaScript .

Axios cross-domain common errors

Cross-Origin Request Blocked:

This is an error caused by the same-origin policy implemented by the browser. Browsers by default do not allow requests to be sent from one origin to another unless explicitly authorized by the target server. Without any cross-domain resolution, the browser intercepts the request and reports this error.

Unable to obtain response content (No 'Access-Control-Allow-Origin' header is present on the requested resource) :

When using the CORS (Cross-Origin Resource Sharing) solution, the server needs to add Access-Control-Allow-Origin header information in the response header to indicate the source that is allowed to access the resource. If the server does not configure this header information correctly or configures it incorrectly, the browser will report this error, indicating that the response content cannot be obtained without authorization.

A network error occurred in the request (Network Error):

When a network error occurs when a cross-domain request is sent (such as the target server is inaccessible, request timeout, etc.), Axios will capture this error , and reports it as a "Network Error".

Preflight request failed:

When using CORS to initiate some complex requests (such as with custom header information or using PUT, DELETE and other non-simple request types) , the browser will send an OPTIONS preflight request before sending the actual request. If the server does not handle the OPTIONS request correctly or does not return the correct preflight response headers, the browser will report a "Preflight request failed" error.

Proxy server error:

If you use a proxy server as a solution and the proxy server is misconfigured or unavailable, Axios may report errors related to the proxy server connection.

Axios cross-domain solution

1. CORS

CORS requires the server to set the Access-Control-Allow-Origin response header, indicating that the resource can be accessed cross-domain by the specified domain.

 
 
// 服务端代码
res.setHeader('Access-Control-Allow-Origin', '*'); 

2. Enable CORS on the server

For example, Node.js Express enables CORS:

 
 
const express = require('express')
const app = express()

app.use(function (req, res, next) {

  // 启用 CORS
  res.header('Access-Control-Allow-Origin', '*');

  next();  
})

3. JSONP

The principle of JSONP is dynamic insertion

 
 
    import axios from 'axios';

axios.get('/api/user?callback=fetchUser');

function fetchUser(user) {
  console.log(user); 
}

The server returns JSON data with function call:

 
 
  fetchUser({
  name: 'jack'
})

4. Proxy server

In the development environment, you can start a proxy server locally to achieve cross-domain access. In the following example, the client can obtain data on the target server by accessing the proxy server's /api/data route.

 
 
    // Node.js 代理服务器
const express = require('express');
const axios = require('axios');
const app = express();
const port = 3000;

app.use(express.json());

app.get('/api/data', async (req, res) => {
  try {
    const response = await axios.get('https://目标服务器的URL/data');
    res.json(response.data);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch data from the target server' });
  }
});

app.listen(port, () => {
  console.log(`Proxy server is running on http://localhost:${port}`);
});

Axios cross-domain code example

Suppose there is an API that requires cross-domain access:

 
 
  
axios.get('http://cross-domain-api.com/users')

You can start an Express proxy server on local port 3000:

 
 
    const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

app.use('/api', createProxyMiddleware({ 
  target: 'http://cross-domain-api.com', // 跨域目标接口
  changeOrigin: true 
}))

app.listen(3000);

Then modify the axios request address to point to the proxy server:

 
 
axios.get('http://localhost:3000/api/users')
 
 
## 提示与注意事项
  • When choosing a cross-domain solution, choose the most appropriate approach considering the complexity and needs of your project.
  • JSONP only supports GET requests and is not suitable for all scenarios.
  • CORS requires server-side support and may not be fully supported in some older versions of browsers.

Debugging the backend interface using Apifox

Apifox = Postman + Swagger + Mock + JMeter, Apifox supports debugging http(s), WebSocket, Socket, gRPC, Dubbo and other protocols interface, and integrates the IDEA plug-in. When the back-end personnel finish writing the service interface, Apifox can be used to verify the correctness of the interface during the testing phase. The graphical interface greatly facilitates the efficiency of project launch.

Summarize

Commonly used Axios cross-domain solutions include CORS, JSONP, proxy, etc. The development environment can achieve cross-domain through a proxy server. CORS requires the server to set the Access-Control-Allow-Origin response header, and JSONP only supports GET requests. Choosing a solution that suits the project needs can well solve cross-domain problems and ensure the normal operation of the application.

Knowledge expansion:

References:

Guess you like

Origin blog.csdn.net/LiamHong_/article/details/132901293