寫一個config.js文件,作為項目地址的配置。
1 //項目域名地址 2 const url = 'https://exaple.com'; 3 4 5 let ROOT; 6 //由於封裝的axios請求中,會將ROOT打包進去,為了方便之后不再更改,判斷了當前環境,而生成的不同的ROOT 7 if (process.env.NODE_ENV === 'development') { 8 //開發環境下的代理地址,解決本地跨域跨域,配置在config目錄下的index.js dev.proxyTable中 9 ROOT = "/apis" 10 } else { 11 //生產環境下的地址 12 ROOT = url; 13 } 14 15 exports.PROXYROOT = url; //代理指向地址 16 exports.ROOT = ROOT;
這里暴露出去了兩個接口,一個作為代理指向地址,也就是真正的請求地址,一個則為我們的ajax請求的地址。
我們將ROOT引入我們配置的ajax中,再將proxyConfig.js修改如下:
1 const config = require("../src/fetch/config"); //路徑你們改下 2 module.exports = { 3 proxy: { 4 [config.ROOT]: { //將www.exaple.com印射為/apis 5 target: config.PROXYROOT,, // 接口域名 6 secure: false, // 如果是https接口,需要配置這個參數 7 changeOrigin: true, //是否跨域 8 pathRewrite: { 9 [`^${config.ROOT}`]: '' //需要rewrite的 10 } 11 } 12 } 13 }

參考文章
https://segmentfault.com/a/1190000011007043
https://blog.csdn.net/hyupeng1006/article/details/81810545
