1. 程式人生 > 其它 >react 配置 setupProxy.js 後網頁無法開啟?404

react 配置 setupProxy.js 後網頁無法開啟?404

問題程式碼復現:

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': ''}
    })
  )
}

原因分析:

http-proxy-middleware的版本如果是1.x以上,需要這麼寫:

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

A little hug, little gift. All of little something. these are our meories.