安装http-proxy-middleware
npm install http-proxy-middleware --save
进行配置
安装middleware插件后,在src目录中新建setupProxy.js文件,在文件中放入如下代码:
const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = function (app) {
app.use(createProxyMiddleware('/api', {
target: 'http://localhost:3000',
secure: false,
changeOrigin: true,
pathRewrite: {
"^/api": "/api"
}
}))
}
简单来说就是当接口是以/api开头才用代理。
比如:
本来是在localhost:8080启动的react,
axios.get("/api/a")请求,最后代理路径就是http://localhost:3000/api/a
pathRewrite : 路径重写功能 默认的好像是pathRewrite: {
"^/xxx": ""} 这个xxx是和createProxyMiddleware()第一个参数对应的。
上诉例子就是当匹配到/api开头的接口,开头的 /api不变,比如用前端请求数据url地址为"/api/b",实际上请求地址为"http://localhost:3000/api/b";
如果上诉例子这样写 pathRewrite: {"^/api": ""} 意思就是开头的 /api 变成了 ""(空字符串),比如用前端请求数据url地址为"/api/b",实际上请求地址为"http://localhost:3000/b",
这个功能相当于js中的replace功能
然后运行项目
npm run start
想看更多的博客,请到该 博客