一、什么是跨域
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>
重啟服務后,點擊按鈕,可以成功訪問,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/175408.html
標籤:JavaScript
