1、先安裝http-proxy-middleware
npm i http-proxy-middleware
在src文件夾下創建setupProxy.js文件,以下爲代碼,有詳細註釋
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
// /api 表示代理路徑
// target 表示目標服務器的地址
app.use(
proxy('/users', {
// http://localhost:8080/ 地址只是示例,實際地址以項目爲準
target: 'http://localhost:5001/',
// 跨域時一般都設置該值 爲 true
changeOrigin: true,
// 重寫接口路由
// pathRewrite: {
// '^/api': '' // 這樣處理後,最終得到的接口路徑爲: http://localhost:8080/xxx
// }
})
)
}
2、create-react-app 的版本在低於 2.0 的時候可以在 package.json 增加 proxy 配置, 配置成如下:
"proxy":{
"/manage":{
"target":"http://admintest.happymmall.com",
"changeOrigin": true
}
}
create-react-app 的版本高於 2.0 版本的時候在 package.json 只能配置 string 類型, 配置成如下:
"proxy": "http://www.wyunfei.com" // 配置你要請求的服務器地址