前言
如果你有單獨的后端開發服務器 API,并且希望在同域名下發送 API 請求 ,那么代理某些 URL 會很有用。
解決開發環境的跨域問題(不用在去配置nginx和host, 爽歪歪~~)
在webpack.config.js中配置
下面簡單介紹一下五個經常使用的場景
使用一:
mmodule.exports = {  //...  devServer: {    proxy: {      '/api': 'http://localhost:3000'    }  }};請求到 /api/xxx 現在會被代理到請求 http://localhost:3000/api/xxx, 例如 /api/user 現在會被代理到請求 http://localhost:3000/api/user
使用二
如果你想要代碼多個路徑代理到同一個target下, 你可以使用由一個或多個「具有 context 屬性的對象」構成的數組:
module.exports = {  //...  devServer: {    proxy: [{      context: ['/auth', '/api'],      target: 'http://localhost:3000',    }]  }};使用三:
如果你不想始終傳遞 /api ,則需要重寫路徑:
module.exports = {  //...  devServer: {    proxy: {      '/api': {        target: 'http://localhost:3000',        pathRewrite: {'^/api' : ''}      }    }  }};請求到 /api/xxx 現在會被代理到請求 http://localhost:3000/xxx, 例如 /api/user 現在會被代理到請求 http://localhost:3000/user
使用四:
默認情況下,不接受運行在 HTTPS 上,且使用了無效證書的后端服務器。如果你想要接受,只要設置 secure: false 就行。修改配置如下:
module.exports = {  //...  devServer: {    proxy: {      '/api': {        target: 'https://other-server.example.com',        secure: false      }    }  }};使用五:
有時你不想代理所有的請求??梢曰谝粋€函數的返回值繞過代理。
在函數中你可以訪問請求體、響應體和代理選項。必須返回 false 或路徑,來跳過代理請求。
例如:對于瀏覽器請求,你想要提供一個 HTML 頁面,但是對于 API 請求則保持代理。你可以這樣做:
module.exports = { //...  devServer: {    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';          }        }      }    }  }  };解決跨域原理
上面的參數列表中有一個changeOrigin參數, 是一個布爾值, 設置為true, 本地就會虛擬一個服務器接收你的請求并代你發送該請求,
module.exports = {  //...  devServer: {    proxy: {      '/api': {        target: 'http://localhost:3000',        changeOrigin: true,      }    }  }};            
新聞熱點
疑難解答
圖片精選