React脚手架设置代理配置
如果porxy只代理一个,可直接更改package.json文件
增加"proxy": "http://192.168.10.99:8086"即可
...
"eslintConfig": {
"extends": "react-app"
},
"proxy": "http://192.168.10.99:8086",
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
...
此时使用Axios.post等请求方式时,直接将"http://192.168.10.99:8086"删除即可,无论是路由还是组件都不需更改其他操作
//Axios.get("http://192.168.10.99:8086/ChatRecord/getConsultingChatRecords)
Axios.get("/ChatRecord/getConsultingChatRecords)
.then((res) => {
console.log(res)
)}
如果porxy代理多个,需在项目中安装http-proxy-middleware
1.使用npm安装依赖
npm i http-proxy-middleware -d
2.在项目src中新建一个js文件,命名为setupProxy.js
3.在文件中加入以下代码
const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = function (app) {
app.use("/api",
createProxyMiddleware({
target: 'http://192.168.10.99:8086',
changeOrigin: true,
pathRewrite: {
"^/api": ""
}
})
);
app.use("/apc",
createProxyMiddleware({
target: 'http://192.168.10.99:8088',
changeOrigin: true,
pathRewrite: {
"^/apc": ""
}
})
)
}
4.请求时,将代理网址更改为/api或/apc等即可正常访问
Axios.get("/api/ChatRecord/getConsultingChatRecords)
.then((res) => {
console.log(res)
)}
5.在控制台可以看到虽然显示的是访问locolhost,但是已经可以正常返回数据
- 如果没有安装http-proxy-middleware时,在package文件中配置proxy代理多个时,会出现报错
如果在操作过程中接口没有反应时,需重启项目,全部设置完毕之后重启即可