Vue之Axios跨域問題解決方案

// axios 中的GET請求
axios.get('/user', {
    params: {
      ID: ‘001’
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// axios 中的POST請求
axios.post('/user', {
    firstName: '1',
    lastName: '2'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

方案1:既然使用axios直接進行跨域訪問不可行,我們就需要配置代理了。代理可以解決的原因:因爲客戶端請求服務端的數據是存在跨域問題的,而服務器和服務器之間可以相互請求數據,是沒有跨域的概念(如果服務器沒有設置禁止跨域的權限問題),也就是說,我們可以配置一個代理的服務器可以請求另一個服務器中的數據,然後把請求出來的數據返回到我們的代理服務器中,代理服務器再返回數據給我們的客戶端,這樣我們就可以實現跨域訪問數據。

準備工作:安裝所需中間件和插件等,比如axios,http-proxy-middleware等。

具體案例:這裏以訪問豆瓣Top250爲例,直接訪問如下:

axios.get("http://api.douban.com/v2/movie/top250")
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(err)
})

當執行npm run dev時,控制檯報錯如下:

Vue之Axios跨域問題解決方案

事實證明直接請求確實出現跨域問題了,下面具體演示解決跨域問題的步驟:

上面所說的必備條件都已安裝完成的情況下,執行以下步驟即可解決問題:

1.配置BaseUrl

在main.js中,配置數據所在服務器的前綴(即固定部分),代碼如下:

// 項目入口,配置全局vue
import Vue from 'vue'
import VueRouter from './router/routes.js'
import Store from './store/index.js'

import './assets/less/index.less'
import App from './App.vue'

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'

import axios from 'axios'
Vue.prototype.$axios = axios
axios.defaults.baseURL = '/api'  //關鍵代碼
Vue.config.productionTip = false

Vue.use(ElementUI);

new Vue({
    router:VueRouter,
    store:Store,
    template:'<App/>',
    components: {App}
}).$mount('#app')

// 默認進入商品模塊
// VueRouter.push({ path: '/home' })

關鍵代碼:axios.defaults.baseURL = '/api',作用是我們每次發送的請求都會帶一個/api的前綴。

2.配置代理

在config文件夾下的index.js文件中的proxyTable字段中,作如下處理:

  dev: {
    env: require('./dev.env'),
    port: 8090,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target:'http://api.douban.com/v2', // 你請求的第三方接口
        changeOrigin:true, // 在本地會創建一個虛擬服務端,然後發送請求的數據,並同時接收請求的數據,這樣服務端和服務端進行數據的交互就不會有跨域問題
        pathRewrite:{  // 路徑重寫,
          '^/api': ''  // 替換target中的請求地址,也就是說以後你在請求http://api.douban.com/v2/XXXXX這個地址的時候直接寫成/api即可。
        }
      }
    },
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  }

3.在具體使用axios的地方,修改url如下即可:

 axios.get("/movie/top250").then((res) => {
                  res = res.data
                  if (res.errno === ERR_OK) {
                     this.themeList=res.data;
                  }
                }).catch((error) => {
                  console.warn(error)
                })

4.重新啓動項目之後,已經解決了跨域問題,結果如下:
【注意】:必須重啓項目!!

原理:

因爲我們給url加上了前綴/api,我們訪問/movie/top250就當於訪問了:localhost:8080/api/movie/top250(其中localhost:8080是默認的IP和端口)。

在index.js中的proxyTable中攔截了/api,並把/api及其前面的所有替換成了target中的內容,因此實際訪問Url是http://api.douban.com/v2/movie/top250。

至此,純前端配置代理解決axios跨域得到解決。

根據評論區內容,區分一下生產環境和開發環境,集體配置如下:

1.在config文件夾裏面創建一個api.config.js的配置文件

const isPro = Object.is(process.env.NODE_ENV, 'production')

console.log(isPro);

module.exports = {
baseUrl: isPro ? 'https://www.***/index.php/Official(線上地址)' : 'api/'
}
2.在main.js文件裏面引入上面文件,這樣就可以保證動態的匹配生產和開發環境的定義前綴了,代碼如下:

import Vue from 'vue'
import App from './App'
import router from './router'
import 'bootstrap/dist/js/bootstrap.min'
import 'bootstrap/dist/css/bootstrap.min.css'
import axios from 'axios'
import apiConfig from '../config/api.config'

Vue.prototype.$axios = axios;
Vue.config.productionTip = false;
axios.defaults.baseURL = apiConfig.baseUrl;// 配置接口地址
axios.defaults.withCredentials = false;
以上兩步即可解決vue的跨域問題,並且可以可以直接build打包到線上,如有問題,請評論區留言,希望對你有所幫助。

點贊 20

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章