方法一
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.調用接口,重啟項目