喜欢我的话,点击上方蓝色文字关注吧?
Vue:
在根目录下(和package.json同级)新建文件vue.config.js,配置如下:
module.exports = { devServer: { proxy: { '/api': { target: 'http://xxx', //转发到的域名或者ip地址 pathRewrite: { '^/api': '' //接口地址里没有"/api",将其重写置空 } } } }}
这样,我们在请求接口的时候,接口地址格式写成:"/api/xxx/xxx"
React
react推荐用http-proxy-middleware中间件
安装http-proxy-middleware,命令如下:
npm install http-proxy-middleware
安装成功之后,在src目录下新建文件setupProxy.js,配置如下:
const {createProxyMiddleware} = require('http-proxy-middleware');module.exports = function(app) { app.use(createProxyMiddleware('/api', { target: 'http://xxx', //转发到的域名或者ip地址 pathRewrite: { '^/api': '', //接口地址里没有"/api",将其重写置空 }, changeOrigin: true, //必须设置为true secure: false //是否验证https的安全证书,如果域名是https需要配置此项 }));};
同样,接口地址格式为:"/api/xxx/xxx"
无论vue还是react,以上配置方法都可以配置多项,比如:
vue:
module.exports = { devServer: { proxy: { '/api': { target: 'http://xxx', //转发到的域名或者ip地址 pathRewrite: { '^/api': '' //接口地址里没有"/api",将其重写置空 } }, '/client': { target: 'http://xxx', //转发到的域名或者ip地址 pathRewrite: { '^/client': '' //接口地址里没有"/client",将其重写置空 } } } }}
react:
const {createProxyMiddleware} = require('http-proxy-middleware');module.exports = function(app) { app.use(createProxyMiddleware('/api', { target: 'http://xxx', pathRewrite: { '^/api': '', }, changeOrigin: true, secure: false })); app.use(createProxyMiddleware('/client', { target: 'http://xxx', pathRewrite: { '^/client': '', }, changeOrigin: true, secure: false }));};
注意:配置完后需要重新运行一下才会生效。
往期 精彩 回顾