React脚手架设置代理配置 - Go语言中文社区

React脚手架设置代理配置


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代理多个时,会出现报错
    如果在操作过程中接口没有反应时,需重启项目,全部设置完毕之后重启即可
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/Darker0305/article/details/111594127
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢