在react脚手架中配置代理一般有两种方式
一、通过package.json配置
在package.json中增加以下配置
"proxy":"http://localhost:5000"
通过package.json配置代理的说明
- 配置简单,前端请求资源时可以不加任何前缀
- 不可以配置多个代理
- 配置以后,当请求了3000不存在的资源时,那么该请求会转发给5000 (优先匹配前端资源)
二、通过代理配置文件
- 第一步:在src下创建代理配置文件setupProxy.js,该js不可以更换名称
- 在setupProxy.js中配置具体代理规则
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':''}//去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置)
})
),
app.use(
proxy('/api2',{
target:'http://localhost:5001',
changeOrigin:true,
pathRewrite:{'^/api1':''}
})
)
}
通过代理配置文件进行代理配置说明
- 可以配置多个代理,可以灵活的控制请求是否走代理
- 前端请求资源时必须加前缀
前端请求示例
import React, { Component } from 'react';
import axios from 'axios'
class App extends Component {
getFoodTypeData=()=>{
axios.get('http://localhost:3000/api1/foodtypes').then(
response=>{
console.log('成功了',response.data);
},
error=>{
console.log('失败了',error)
}
)
}
getCarData=()=>{
axios.get('http://localhost:3000/api2/cars').then(
response=>{
console.log('成功了',response.data);
},
error=>{
console.log('失败了',error)
}
)
}
render() {
return (
<div>
<button onClick={this.getStudentData}>点击获取食品种类</button>
<button onClick={this.getCarData}>点击获取汽车品牌</button>
</div>
);
}
}
export default App;