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>

 

重啟服務后,點擊按鈕,可以成功訪問。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM