1. 程式人生 > >vue 本地環境API代理設定和解決跨域

vue 本地環境API代理設定和解決跨域

寫一個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