main.js配置
import Axios from 'axios'
Axios.defaults.method = 'GET'//設置默認的請求類型
Axios.defaults.baseURL = 'https://apis.jxcxin.cn/api'//設置接口地址
Axios.defaults.params = { token: 'abc' } //每次請求都帶上這個參數
Axios.defaults.timeout = 5000 //請求的超時時間
Vue.prototype.$axios = Axios
簡化接口地址
配置了baseURL 直接寫路徑即可
this.$axios.get('/title',//直接寫路徑即可{params: {id: 10}}).then(res => {console.log(res)})
多臺服務器配置
如果存在多臺服務器,有多個接口使用 Axios.defaults.baseURL 就直接寫死了,這個時候可以二次封裝要一下,
例如:登錄,或數據處理不是同一個服務器上的
import Axios from 'axios'Vue.prototype.$axiosServ1 = Axios.create({baseURL: 'www.BAIDU.com'
})Vue.prototype.$axiosServ2 = Axios.create({baseURL: 'www.avc.com'
})
this.$axiosServ1.get('www.baidu.com').then(res => {console.log(res)})//服務器1this.$axiosServ2.get('www.baidu.com').then(res => {console.log(res)})//服務器2