如果你有單獨的后端開發服務器 API,並且希望在同域名下發送 API 請求 ,那么代理某些 URL 會很有用。
dev-server 使用了非常強大的 http-proxy-middleware 包。更多高級用法,請查閱其文檔。
在 localhost:3000
上有后端服務的話,你可以這樣啟用代理:
proxy: { "/api": "http://localhost:3000" }
請求到 /api/users
現在會被代理到請求 http://localhost:3000/api/users
。
如果你不想始終傳遞 /api
,則需要重寫路徑:
proxy: { "/api": { target: "http://localhost:3000", pathRewrite: {"^/api" : ""} //后面可以使重寫的新路徑,一般不做更改 } }
默認情況下,不接受運行在 HTTPS 上,且使用了無效證書的后端服務器。如果你想要接受,修改配置如下:
proxy: { "/api": { target: "https://other-server.example.com", secure: false } }
有時你不想代理所有的請求。可以基於一個函數的返回值繞過代理。
在函數中你可以訪問請求體、響應體和代理選項。必須返回 false
或路徑,來跳過代理請求。
例如:對於瀏覽器請求,你想要提供一個 HTML 頁面,但是對於 API 請求則保持代理。你可以這樣做:
proxy: { "/api": { target: "http://localhost:3000", bypass: function(req, res, proxyOptions) { if (req.headers.accept.indexOf("html") !== -1) { console.log("Skipping proxy for browser request."); return "/index.html"; } } } }
如果你使用的vue-cli開發 他同樣提供了 proxyTable 和上面的操作一樣
以下是我出於無奈改造的
const targetPath='http://172.16.3.48:8080';//服務器的地址 可以是www.xxx.com const pathX='/*';//如果打包后接口地址為fwone-central/orderinfo/* 則pathX='/*' 如果是/orderinfo/* 則pathX='' var keysArr=[ pathX+'/orderinfo/*', pathX+'/company/*', pathX+'/person/*', pathX+'/person/*/*', pathX+'/oncall/*', pathX+'/Tr/*', pathX+'/calldetail/*', pathX+'/customernotification/*', pathX+'/customernotification/*/*/*', pathX+'/sys/*', pathX+'/sys/*/*', pathX+'/invoice/*', pathX+'/contractservicedetails/*', pathX+'/customercomplain/*', pathX+'/callreminder/*', ] for(let i=0;i<keysArr.length;i++){ config.dev.proxyTable[keysArr[i]]={ target:targetPath, secure: false, changeOrigin: true, } } console.info(Object.keys(config.dev.proxyTable)) module.exports= config
我先說一下我為什么這么做,我們本地開發直接常規的寫法沒有問題但是如果部署到測試服務器上,一個tomcat跑多個項目我們后端是用文件夾來區分項目的,但是這個區分后似乎會影響接口路徑 ,也就是說
原本是‘/’ 現在變成了 ‘/fwone-central’
我一開始以為這樣也很好解決 我直接把target 改成 'http://172.16.3.48:8080/fwone-central' 接口報404
然后
'/fwone-central/orderinfo/*': { target:'http://172.16.3.48:8080', secure: false, changeOrigin: true, }, //這樣又ok 其實我看請求的地址是一樣一樣的
所以我無奈做了上面的修改 也許你不知道我在說什么,因為你沒有遇到過,或者你永遠遇不到.
當然上面的問題還有坑 當你在請求數據的時候,原本是這樣的沒有問題 ,但是你部署后路徑改變了,這個請求路徑也就無效了
axios({ method: 'get', url:'/orderinfo/count' , params: {orderStateIds: [1, 2, 3, 4, 5, 6, 7, 8]} }).then(function (r) { if (r.data.code == 0) { //... } }); }).catch(function (error) { console.error(error); })
解決辦法,是有流傳已久的絕對路徑和公共路徑
window.localPath='http://localhost:8087/fwone-central' //他可以定義在首頁隨時順着項目路徑修改 axios({ method: 'get', url:localPath+'/orderinfo/count' , params: {orderStateIds: [1, 2, 3, 4, 5, 6, 7, 8]} }).then(function (r) { if (r.data.code == 0) { //... } }); cb() }).catch(function (error) { console.error(error); })
還有最后一點需要注意路徑改變了打包后的靜態資源路徑也得改變 所以在vue-cli config.js index.js
build: { assetsSubDirectory: 'statics/mobile', //這是將靜態資源打包到指定的文件夾下 assetsPublicPath:'/fwone-central/', // 這是靜態資源的路徑 },
當然上面的絕對路徑可以通過axios的全局配置來設置。