React local testing - solving cross-domain issues

Written in the front: The blogger is a "little mountain pig" who has devoted himself to the training business after actual development and experience. His nickname is taken from "Peng Peng" in the cartoon "The Lion King". He always treats the surrounding people with an optimistic and positive attitude. thing. My technical route has gone all the way from a Java full-stack engineer to the field of big data development and data mining. Now I have achieved some success. I would like to share with you what I have gained in the past. I hope it will be helpful to you on the way of learning. At the same time, the blogger also wants to build a complete technical library through this attempt. Any exceptions, errors, and precautions related to the technical points of the article will be listed at the end. You are welcome to provide materials in various ways.

  • Please criticize and point out any mistakes in the article, and correct them in time.
  • If you have any questions you want to discuss and learn, please contact me: [email protected].
  • The style of publishing articles varies from column to column, and they are all self-contained. Please correct me if there are any deficiencies.

React local testing - solving cross-domain issues

Keywords in this article: React, testing, cross-domain

1. Problem description

Recently, React was used for front-end interface development, and then interface testing. Since it is a separate front-end and back-end project, I first used some Mock Server tools to replace the back-end interface data return, so that the page can be organized relatively quickly, and finally it is only necessary to complete the docking of the actual interface. However, the general solution to cross-domain problems is to add corresponding configurations on the server side. Here, we will introduce how to solve cross-domain problems in React projects alone .

Second, the cause

I didn't study the cross-domain problem carefully before, so I checked some information and recorded it together. The cross-domain problem is caused by the same-origin policy [Same-Origin Policy] of the browser, and has nothing to do with the specific technology used.
The same-origin policy is a browser security mechanism designed to prevent malicious data access between different sources (domain names, protocols, ports). The same-origin policy requires that scripts in web pages can only access resources under the same origin, and cannot directly access resources of other origins. When we are running some front-end and back-end classified projects, usually the front-end and back-end services are running on different ports , which will cause cross-domain.
When a browser initiates a cross-origin request, it sends a preflight request (OPTIONS request), which is used to ask the server whether to accept requests from different sources. The server can control whether to allow cross-origin requests through the CORS (Cross-Origin Resource Sharing) policy in the response header. If the server does not configure the CORS policy correctly, the browser will reject cross-origin requests.

3. Solutions

My React runs on localhost:3000 , and the backend service runs on localhost:2000 , based on this premise.

1. package.json

Add the following content at the end of the file, pay attention to splicing commas:

    "proxy": "http://localhost:2000"

2. setupProxy.js

Create a new setupProxy.js file under src , which will be automatically read when the project starts.

Before editing the file, you can install the required dependencies first, or you can follow the prompts to install:

npm install http-proxy-middleware

Write the following content in the file, which will proxy to the required interface address when requesting the corresponding interface:

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

module.exports = function(app) {
    
    
    app.use(
        '/user/selectOne',
        createProxyMiddleware({
    
    
            target: 'http://localhost:2000',  // 后端接口的地址
            changeOrigin: true,
        })
    );
};

The advantage of this is that each interface can be specified accurately without affecting the routing jump, but if there are many interfaces, it will be cumbersome. You can write a method to traverse:

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

const proxyConfig = [
  {
    
    
    path: '/user/selectOne',
    target: 'http://localhost:2000',
  },
  {
    
    
    path: '/user/selectAll',
    target: 'http://localhost:2000',
  },
  // 添加更多的代理规则
];

module.exports = function(app) {
    
    
  proxyConfig.forEach(proxy => {
    
    
    app.use(
      proxy.path,
      createProxyMiddleware({
    
    
        target: proxy.target,
        changeOrigin: true,
      })
    );
  });
};

In this way, we only need to add the path mapping in proxyConfig every time , which is quite convenient.

3. service.ts

When requesting an interface, you do not need to specify the interface address, but directly use the interface path:

import axios from 'axios';

interface LoginParams {
    
    
    username: string;
    password: string;
}

interface LoginResponse {
    
    
    status: number;
}

export const loginUser = async ({
    
     username, password }: LoginParams): Promise<LoginResponse> => {
    
    
    const response = await axios.get<LoginResponse>("/user/selectOne", {
    
    
        params: {
    
    
            username,
            password,
        },
    });
    return response.data;
};

Scan the QR code below, join the official CSDN fan WeChat group, you can communicate with me directly, and there are more benefits~
insert image description here

Guess you like

Origin blog.csdn.net/u012039040/article/details/131799853