webpack 前後端分離開發介面除錯解決方案,proxyTable解決方案
如果你有單獨的後端開發伺服器 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); })
素材公社https://www.wode007.com/sites/73209.html 愛圖網https://www.wode007.com/sites/73208.html
解決辦法,是有流傳已久的絕對路徑和公共路徑
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.jsindex.js
build: { assetsSubDirectory: 'statics/mobile', //這是將靜態資源打包到指定的資料夾下 assetsPublicPath:'/fwone-central/', // 這是靜態資源的路徑 },
當然上面的絕對路徑可以通過axios的全域性配置來設定。