1. 程式人生 > 實用技巧 >本地axios處理跨域問題(僅針對vue-cli3以下的開發環境,專案中配置檔案是config->index.js)

本地axios處理跨域問題(僅針對vue-cli3以下的開發環境,專案中配置檔案是config->index.js)

首先npm安裝好axios,其次在main.js中引入:

1 import axios from 'axios'
2 
3 Vue.prototype.$axios = axios    //把axios掛載到vue的原型中,在vue中每個元件都可以使用axios傳送請求
4 Vue.prototype.HOME = '/api'    //重要在於這裡,Vue.prototype.HOME = '/api'是一個定值,預設指向localhost,所有修改指向路徑為'/api',配置檔案index.js定義的可跨域路徑

第二步就是修改上述所說的config>index.js配置檔案:

 1 module.exports = {
2 dev: { 3 // Paths 4 assetsSubDirectory: 'static', 5 assetsPublicPath: '/', 6 proxyTable: { //axios跨域處理 7 '/api': { //此處並非和url一致 8 target:'http://192.168.2.80:8081/', 9 changeOrigin:true, //允許跨域 10 pathRewrite:{ 11 '^/api': '' 12 }
13 } 14 } 15 } 16 ....以下省略 17 }

最後就是在需要跨域的檔案中操作了:

 1     created() {
 2       var url = this.HOME + '/index***ds/getFe***List';  //HOME變數為已掛載的可跨域域名,這裡將其拼接完,成為一個完整路徑
 3       this.$axios({  //this代表vue物件,之前在入口檔案中把axios掛載到了vue中,所以這裡直接用this.$axios呼叫axios物件
 4         method: 'post',
 5         url: url,
6 data: {feedType: 1, page: 1, pagesize: 10} 7 }).then(function (res) { 8 console.log(res); 9 }).catch(function (err) { 10 console.log(err); 11 }) 12 },

這樣就可以成功跨域,拿到後臺返回的資料了。

需要注意的是:在Vue專案中如果我們修改了config裡面的檔案,請千萬要重新啟動專案,重新啟動專案,重新啟動專案,不然一定會報錯。

當然,這只是在本地可以正常跨域訪問介面,線上的話,還需要和後臺協商處理。線上推薦用Nginx。(後續會發布相關知識)