1. React itself focuses only on the interface and does not contain the code to send ajax requests
  2. The front-end application needs to interact with the backend through Ajax requests (JSON data)
  3. React applications need to integrate third-party Ajax libraries or encapsulate their own libraries

Common Ajax libraries:

  1. JQuery: Not recommended because it is heavy
  2. Axios: Lightweight advice
    • Ajax that encapsulates xmlHttpRequest objects
    • Promise style
    • It can be used on the browser side and node server side

Configuring the Proxy Server

Methods a

Add the following configuration to package.json

"proxy":"http://localhost:5000"
Copy the code

Description:

  1. Advantages: Simple configuration and no prefix can be added when the front-end requests resources.
  2. Disadvantages: You cannot configure multiple agents.
  3. How it works: Configure the proxy so that when 3000 resources are requested that do not exist, the request is forwarded to 5000 (matching front-end resources is preferred).

Method 2

  1. Step 1: Create the proxy profile

    Create a configuration file under SRC: SRC/setupproxy.jsCopy the code
  2. Write setupproxy.js to configure specific proxy rules:

    const proxy = require('http-proxy-middleware')
    
    module.exports = function(app) {
      app.use(
        proxy('/api1', {  // API1 is the request that needs to be forwarded (all requests with/API1 prefix are forwarded to 5000)
          target: 'http://localhost:5000'.// Configure the forwarding target address (the server address that can return data)
          changeOrigin: true.// Controls the value of the host field in the request header received by the server
          /* When changeOrigin is set to true, the host in the request header received by the server is: localhost:5000 The default changeOrigin value is false, but we usually set the changeOrigin value to true */
          pathRewrite: {'^/api1': ' '} // Remove the request prefix to ensure that the backend server is normal request address (must be configured)
        }),
        proxy('/api2', { 
          target: 'http://localhost:5001'.changeOrigin: true.pathRewrite: {'^/api2': ' '}}}))Copy the code

Description:

  1. Advantages: Multiple proxies can be configured to flexibly control whether requests go through proxies.
  2. Disadvantages: Cumbersome configuration and prefix must be added when the front-end requests resources.