current position:Home>React configuration agent

React configuration agent

2022-04-29 06:22:01Tool man of konjaku

Method 1

stay package.json The following configuration is added in

"proxy":"http://localhost:5000"

Pay attention to !

// Local is 3000 Turn on 
fetch('http://localhost:3000/*')

explain :

  1. advantage : Simple configuration , The front end can request resources without any prefix .
  2. shortcoming : Cannot configure multiple agents .
  3. Operation mode : Configure the agent as described above , When asked 3000 When there are no existing resources , Then the request will be forwarded to 5000 ( Priority matching front-end resources )

Method 2

  1. First step : Create a proxy profile

     stay src Create profile under :src/setupProxy.js
    
  2. To write setupProxy.js Configure specific proxy rules :

    const proxy = require('http-proxy-middleware')
    
    module.exports = function(app) {
          
      app.use(
        proxy('/api1', {
            //api1 It's a request that needs to be forwarded ( All with /api1 All prefix requests are forwarded to 5000)
          target: 'http://localhost:5000', // Configure forwarding destination address ( The address of the server that can return the data )
          changeOrigin: true, // In the request header received by the control server host Value of field 
          /* changeOrigin Set to true when , In the request header received by the server host by :localhost:5000 changeOrigin Set to false when , In the request header received by the server host by :localhost:3000 changeOrigin The default value is false, But we will generally changeOrigin Value to true */
          pathRewrite: {
          '^/api1': ''} // Remove request prefix , Ensure that the normal request address is given to the background server ( You have to configure )
        }),
        proxy('/api2', {
           
          target: 'http://localhost:5001',
          changeOrigin: true,
          pathRewrite: {
          '^/api2': ''}
        })
      )
    }
    

explain :

  1. advantage : Multiple agents can be configured , It can flexibly control whether the request goes through the proxy .
  2. shortcoming : Complicated configuration , Front end requests for resources must be prefixed .

copyright notice
author[Tool man of konjaku],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/116/202204260949129578.html

Random recommended