方法一
1.安装http-proxy-middleware,下面两种都可。
yarn add http-proxy-middleware //npm install http-proxy-middleware -D
2.在'src'目录下新建'setupProxy.js'文件并写入以下代码(注意第二行注释)
const {createProxyMiddleware} = require('http-proxy-middleware');
//1.0.0版本前都是用proxy,1.0.0后使用porxy会报错,应使用createProxyMiddleware; module.exports = function (app) { app.use( createProxyMiddleware( '/api', { target: 'http://localhost:7001', pathRewrite: {'^/api' : ''}, changeOrigin: true, // target是域名的话,需要这个参数, secure: false, } ) ); };
3.重启服务,调用接口
axios.get('/api/getGoodsMenu').then((res)=>{ console.log(111,res) })
方法二
1.执行npm run eject 弹出配置文件
npm run eject
2.打开webpack.config.js,配置devServer
module.exports = { devServer: { //使用代理进行解决跨域的问题 proxy: {'/api': { target: 'http://127.0.0.1:7001',
pathRewrite:{'^/api' : ''}, changeOrigin: true } } } }
3.调用接口,重启项目