1. 程式人生 > 實用技巧 >12.axios解決跨域問題(vue-cli3)

12.axios解決跨域問題(vue-cli3)

https://www.cnblogs.com/l-y-h/p/11815452.html

axios解決跨域問題(vue-cli3.0)

閱讀目錄


回到頂部

一、什麼是跨域

1、跨域

  指的是瀏覽器不能執行其他網站的指令碼。它是由瀏覽器的同源策略造成的,是瀏覽器對javascript施加的安全限制。

2、同源策略

  是指協議,域名,埠都要相同,其中有一個不同都會產生跨域,在請求資料時,瀏覽器會在控制檯中報一個異常,提示拒絕訪問。

3、跨域問題怎麼出現的

  開發一些前後端分離的專案,比如使用 SpringBoot + Vue 開發時,後臺程式碼在一臺伺服器上啟動,前臺程式碼在另外一臺電腦上啟動,此時就會出現問題。
  比如:

    後臺 地址為 http://192.168.70.77:8081
    前臺 地址為 http://192.168.70.88:8080
  此時 ip 與 埠號不一致, 不符合同源策略,造成跨域問題。

回到頂部


二、使用 axios 演示並解決跨域問題(vue-cli3.0)

1、專案建立、與 axios 的使用

(1)step1:建立 vue 專案
  參考 https://www.cnblogs.com/l-y-h/p/11241503.html

(2)step2:使用 axios

  參考 https://www.cnblogs.com/l-y-h/p/11656129.html

2、跨域問題重現

(1)step1:刪去 vue 專案初始提供的部分程式碼,如下圖

執行截圖:

(2)step2:使用 axios

【App.vue】
<template>
    <div>
        <button @click="testAxios">TestAxios</button>
    </div>
    <!--App -->
</template>

<script>
    // 引入axios
    import Axios from 'axios'

    export default {
        methods: {
            testAxios() {
                const url = 'https://www.baidu.com/'

                Axios.get(url).then(response => {
                    if (response.data) {
                        console.log(response.data)
                    }
                }).catch(err => {
                    alert('請求失敗')
                })
            }
        }
    }
</script>

<style>

</style>

此時點選按鈕,會出現跨域問題。

(3)常見錯誤解決

【question1:】
 'err' is defined but never used (no-unused-vars)
 
 這個問題,是由於 vue 專案安裝了 ESLint 。
 
 暴力解決:直接關閉 ESLint
 在  package.json 檔案中 新增 
 "rules": {
    "generator-star-spacing": "off",
    "no-tabs":"off",
    "no-unused-vars":"off",
    "no-console":"off",
    "no-irregular-whitespace":"off",
    "no-debugger": "off"
}

3、解決跨域問題

(1)step1:配置 baseURL
  可以自定義一個 js 檔案,也可以直接在 main.js 中寫。

【main.js】
import Vue from 'vue'
import App from './App.vue'
// step1:引入 axios
import Axios from 'axios'

Vue.config.productionTip = false

// step2:把axios掛載到vue的原型中,在vue中每個元件都可以使用axios傳送請求,
// 不需要每次都 import一下 axios了,直接使用 $axios 即可
Vue.prototype.$axios = Axios

// step3:使每次請求都會帶一個 /api 字首 
Axios.defaults.baseURL = '/api'

new Vue({
  render: h => h(App),
}).$mount('#app')

(2)step2:修改配置檔案(修改後要重啟服務)
  vue 3.0 通過 vue.config.js 檔案 修改配置(若沒有,則直接在專案路徑下新建即可)。

【vue.config.js】
module.exports = {
    devServer: {
        proxy: {
            '/api': {
                // 此處的寫法,目的是為了 將 /api 替換成 https://www.baidu.com/
                target: 'https://www.baidu.com/',
                // 允許跨域
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        }
    }
}

(3)step3:修改 axios 使用方式

【App.vue】
<template>
    <div>
        <button @click="testAxios">TestAxios</button>
    </div>
    <!--App -->
</template>

<script>
    export default {
        methods: {
            testAxios() {
                // 由於 main.js 裡全域性定義的 axios,此處直接使用 $axios 即可。
                // 由於 main.js 裡定義了每個請求字首,此處的 / 即為 /api/, 
                // 經過 vue.config.js 配置檔案的代理設定,會自動轉為 https://www.baidu.com/,從而解決跨域問題
                this.$axios.get('/').then(response => {
                    if (response.data) {
                        console.log(response.data)
                    }
                }).catch(err => {
                    alert('請求失敗')
                })
            }
        }
    }
</script>

<style>

</style>

重啟服務後,點選按鈕,可以成功訪問。