axios技術總結(包括跨域的處理)

在路上的小小前端程序猿vue經驗分享

1. axios與vue-axios

概念

axios是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中(理解成庫)
vue-axios用於將axios集成到Vuejs的小型包裝器(理解成插件)

安裝

axios:
使用 npm:

npm install axios

使用 bower:

bower install axios

使用 cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

vue-axios:

npm install --save axios vue-axios

使用:
一般來說這兩者需要同時安裝使用
在mian.js中加入以下代碼:

//導入axios vue-axios
import Axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, Axios)

在發起請求的vue文件里加入以下代碼

//三種get請求方式
Vue.axios.get(api).then((response) => {
  console.log(response.data)
})
 
this.axios.get(api).then((response) => {
  console.log(response.data)
})
 
this.$http.get(api).then((response) => {
  console.log(response.data)
})

2.跨域處理

找到config文件中的index.js,修改proxyTable如下:

  dev: {
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api/**': {
          target: 'http://www.bs.com:80',//請求的域名,最好寫完整不然容易出錯
          changeOrigin: true,  //是否跨域
          pathRewrite:{
              '^/api':'/api'
          }
      },
    },

這裏我有個疑惑,pathRewrite我不寫或者寫成這兩種方式都沒報錯

pathRewrite:{
              '^/api':'/api'
         	}
          
pathRewrite:{
			'^/api':'/'
			}

便捷操作:
爲了在用axios發起請求時每次不需要再寫api前綴,在main.js文件加入以下代碼:

Axios.defaults.baseURL = 'api'

這個前綴本應該區分開發環境和生產環境,但是我個人認爲我這項目應該是開發環境,所以沒有動態對不同環境加以匹配。當然我這上面寫的沒有報錯😄

如果跟着上面走了一遍,報錯的話。記得重新npm run dev

以上是我的個人總結,參考了不少資料和大佬博文:
1.https://www.kancloud.cn/yunye/axios/234845
2.https://segmentfault.com/a/1190000011715088
3.`https://www.jianshu.com/p/d65e4d67884a

感謝收看,覺得有用的點贊可好,🤭

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