vue-cli開發環境跨域問題解決方案

來源:互聯網
上載者:User

前後端分離開發中必要會遇到的問題—跨域。在使用vue開發的時候,開始為瞭解決跨域問題。採用的是CORS(Cross-origin resource sharing)。後台在回應標頭中添加Access-Control-Allow-Origin。這樣就可以跨域調後台介面了。
在前幾天無意中看到了config的index.js檔案中有一個proxyTable屬性,通過配置可以解決開發環境的跨域
開發期間的API代理

當將此樣板與現有後端整合時,通常需要在使用dev伺服器時訪問後端API。為了實現這一點,我們可以並行(或遠程)運行dev伺服器和API後端,並讓dev伺服器將所有API請求代理到實際的後端。

要配置代理規則,請在其中編輯dev.proxyTable選項config/index.js。dev伺服器正在使用http代理中介軟體進行代理,因此您應參考其文檔以擷取詳細的用法。但這是一個簡單的例子:

// config/index.jsmodule.exports = {  // ...  dev: {    proxyTable: {      // proxy all requests starting with /api to jsonplaceholder      '/api': {        target: 'http://jsonplaceholder.typicode.com',        changeOrigin: true,        pathRewrite: {  //需要rewrite重寫的, 如果在伺服器端做了處理則可以不要這段          '^/api': ''        }      }    }  }}

上面的樣本將代理請求/api/posts/1到http://jsonplaceholder.typicode.com/posts/1。

如果 pathRewrite: {
‘^/api’: ‘api’
},
則將代理請求/api/posts/1到http://jsonplaceholder.typicode.com/api/posts/1。

網址匹配

除了靜態網址之外,您還可以使用glob模式來匹配URL,例如/api/**。有關詳細資料,請參閱上下文匹配。此外,您可以提供一個filter可以是自訂函數的選項,以確定請求是否應被代理:

proxyTable: {  '*': {    target: 'http://jsonplaceholder.typicode.com',    filter: function (pathname, req) {      return pathname.match('^/api') && req.method === 'GET'    }  }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.