1. 程式人生 > >vue + axios---封裝一個http請求

vue + axios---封裝一個http請求

在使用vue開發時,官方推薦使用axios來請求介面


//    axios官方地址
https://github.com/axios/axios

但是axios並不像 vue-resource 一樣擁有install,即不能直接 Vue.use(axios) 來使用,所以需要我們自己根據axios來寫一個具有install方法的Http庫。

1.安裝axios


npm install axios

2.建立Http.js檔案


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.引用


import Vue from 'vue'
import Http from './Http'

Vue.use(http)

如此,就可以在vue中直接使用axios了

4.axios攔截器
在開發過程中,會需要設定一些請求頭,公共引數等,或者需要對請求結果進行統一處理(例如錯誤處理),這時候就可以用到axios攔截器

建立interceptor.js檔案


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 的原因是方便隨時取消與設定

5.設定axios預設請求地址


axios.defaults.baseURL = 'http://172.0.0.1'

雖說幾乎都是使用webpack代理的方式來配置請求地址,但此方式依然有時會用到

原文地址:https://segmentfault.com/a/1190000017352304