指的是瀏覽器不能執行其餘網站的腳本。它是由瀏覽器的同源策略形成的,是瀏覽器對javascript施加的安全限制。javascript
是指協議,域名,端口都要相同,其中有一個不一樣都會產生跨域,在請求數據時,瀏覽器會在控制檯中報一個異常,提示拒絕訪問。html
開發一些先後端分離的項目,好比使用 SpringBoot + Vue 開發時,後臺代碼在一臺服務器上啓動,前臺代碼在另一臺電腦上啓動,此時就會出現問題。
好比:vue
後臺 地址爲 http://192.168.70.77:8081
前臺 地址爲 http://192.168.70.88:8080
此時 ip 與 端口號不一致, 不符合同源策略,形成跨域問題。java
(1)step1:建立 vue 項目
參考 https://www.cnblogs.com/l-y-h/p/11241503.htmlios
(2)step2:使用 axiosvue-cli
參考 https://www.cnblogs.com/l-y-h/p/11656129.htmljson
(1)step1:刪去 vue 項目初始提供的部分代碼,以下圖axios
運行截圖:後端
(2)step2:使用 axiosapi
【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" }
(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>
重啓服務後,點擊按鈕,能夠成功訪問。