React scaffolding configuration proxy

React scaffolding configuration proxy summary

method one

Add the following configuration to package.json

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

illustrate:

  1. Advantages: Simple configuration, no prefix can be added when the front end requests resources.
  2. Cons: Cannot configure multiple proxies.
  3. Working method: Configure the proxy in the above way. When a resource that does not exist in 3000 is requested, the request will be forwarded to 5000 (matching front-end resources first)

Method Two

  1. Step 1: Create a Proxy Configuration File

    在src下创建配置文件:src/setupProxy.js
    
  2. Write setupProxy.js to configure specific proxy rules:

    const proxy = require('http-proxy-middleware')
    
    module.exports = function(app) {
          
          
      app.use(
        proxy('/api1', {
          
            //api1是需要转发的请求(所有带有/api1前缀的请求都会转发给5000)
          target: 'http://localhost:5000', //配置转发目标地址(能返回数据的服务器地址)
          changeOrigin: true, //控制服务器接收到的请求头中host字段的值
          /*
          	changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
          	changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:3000
          	changeOrigin默认值为false,但我们一般将changeOrigin值设为true
          */
          pathRewrite: {
          
          '^/api1': ''} //去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置)
        }),
        proxy('/api2', {
          
           
          target: 'http://localhost:5001',
          changeOrigin: true,
          pathRewrite: {
          
          '^/api2': ''}
        })
      )
    }
    

illustrate:

  1. Advantages: Multiple proxies can be configured, and it is possible to flexibly control whether requests go through proxies.
  2. Disadvantages: The configuration is cumbersome, and the front end must add a prefix when requesting resources.

Guess you like

Origin blog.csdn.net/weixin_39085822/article/details/120811907
Recommended