在使用vue開發時,官方推薦使用axios來請求接口vue
// axios官方地址 https://github.com/axios/axios
可是axios並不像 vue-resource 同樣擁有install,即不能直接 Vue.use(axios) 來使用,因此須要咱們本身根據axios來寫一個具備install方法的Http庫。webpack
1.安裝axiosios
npm install axios
2.建立Http.js文件git
import axios from 'axios' export default { install (Vue) { // install方法,向Vue實例中添加一個$http方法 Vue.prototype.$http = axios Vue.$http = axios }, $http: axios } export const Http = axios
3.引用github
import Vue from 'vue' import Http from './Http' Vue.use(http)
如此,就能夠在vue中直接使用axios了web
4.axios攔截器
在開發過程當中,會須要設置一些請求頭,公共參數等,或者須要對請求結果進行統一處理(例如錯誤處理),這時候就能夠用到axios攔截器npm
建立interceptor.js文件json
import axios from 'axios' let interceptor = '' export const myInterceptor = interceptor // 設置請求攔截器 export const setInterceptor = function (response) { axios.interceptors.request.use((config) => { config.headers.Authorization = token //設置請求頭Authorization config.headers.Accept = 'application/json' //設置請求頭Accept /* 具體配置須要根據實際開發狀況來配置 */ return config }) } // 移除請求攔截器 export const clearInterceptor = function () { axios.interceptors.request.eject(myInterceptor) }
ps:上例只示範了axios的請求攔截,回覆攔截時一樣的處理方式
ps:在interceptor中暴露myInterceptor、setInterceptor與clearInterceptor 的緣由是方便隨時取消與設置axios
5.設置axios默認請求地址app
axios.defaults.baseURL = 'http://172.0.0.1'
雖然說幾乎都是使用webpack代理的方式來配置請求地址,但此方式依然有時會用到