axios 簡介
axios 是一個基于Promise 用于瀏覽器和 nodejs 的 HTTP 客戶端,它本身具有以下特征:
1、背景
import Vue from 'vue' import axios from 'axios' //項目的一些環境配置參數,讀取host import config from '@/config' //vuex狀態管理,這里主要進行對全局loading的控制 import store from '@/store' //vue-router對相應狀態碼的頁面操作(router實例) import router from '@/router' //console對應封裝 import { log } from '@/utils'
2、解決方案
對于axios的封裝中我們定義幾個參數進行申明
// 加載最小時間 const MINI_TIME = 300 // 超時時間(超時時間) let TIME_OUT_MAX = 5000 // 環境value let _env = process.env.NODE_ENV // 請求接口host let _apiHost = config.api // 請求組(判斷當前請求數) let _requests = []
一般一個項目中的根host和Content-Type都是統一的,這里對axios進行統一的配置(如果這個后端需要formData格式的表單即content-type='application/x-www-form-urlencoded;charset=utf-8'數據,需要對請求數據進行表單序列化,比較快的方式就是引入qs庫qs.stringify進行處理后傳輸)
axios.defaults.headers.common['Content-Type'] = 'application/json' axios.defaults.baseURL = _apiHost
一般情況下項目中同一時刻都會有不止一個請求在進行(還沒有返回),要判斷當前是否還存在進行中的ajax,就需要對_requests這個數組進行維護;
/** * 添加請求,顯示loading * @param {請求配置} config */ function pushRequest(config) { log(`${config.url}--begin`) _requests.push(config) Vue.$vux.loading.show({ text: 'Loading' }) store.dispatch('loading') } /** * 移除請求,無請求時關閉loading * @param {請求配置} config */ function popRequest(config) { log(`${config.url}--end`) let _index = _requests.findIndex(r => { return r === config }) if (_index > -1) { _requests.splice(_index, 1) } if (!_requests.length) { Vue.$vux.loading.hide(0) store.dispatch('loading', false) } }
接下來對axios基于上面的準備進行處理
/** * 請求地址,請求數據,是否靜默,請求方法 */ export default (url, data = {}, isSilence = false, method = 'POST') => { let _opts = { method, url } //通用數據的合并(token) let _data = Object.assign({}, data, { token: store.getters.token }) const _query = {} for (let _key in _data) { if (_data.hasOwnProperty(_key) && _data[_key] !== '') { _query[_key] = _data[_key] } } //axios實例請求定時器ID let _timer = null //判斷請求類型 if (method.toLocaleUpperCase() === 'POST') { _opts.data = _query } else { _opts.params = _query } //返回一個promise return new Promise((resolve, reject) => { //實例化axios const _instance = axios.create({ timeout: TIME_OUT_MAX }) //定義請求的唯一標識 let _random = { stamp: Date.now(), url: `${_apiHost + url}` } //判斷是否靜默(靜默的話就不加入請求標識隊列,不是則申明此請求實例的定時器) if (!isSilence) { _timer = setTimeout(() => { pushRequest(_random) }, MINI_TIME) } //axios實例發送當前請求 //請求完成:1、取消當前請求的定時器;2、在當前請求標識隊列中移除當前標識;
3、成功的話返回統一處理后的數據,失敗則對狀態碼進行判斷
_instance(_opts) .then(res => { let responseData = res.data clearTimeout(_timer) popRequest(_random) resolve(res.data) }) .catch(res => { let _response = res.response let _message = null clearTimeout(_timer) popRequest(_random) switch (_response.status) { case 404: _message = '404,錯誤請求' break case 401: router.push({ path: '/login', query: { redirect: router.currentRoute.fullPath } }) _message = '未授權' break case 403: _message = '禁止訪問' break case 408: _message = '請求超時' break case 500: _message = '服務器內部錯誤' break case 501: _message = '功能未實現' break case 503: _message = '服務不可用' break case 504: _message = '網關錯誤' break default: _message = '未知錯誤' } if (!isSilence) { Vue.$vux.toast.show({ text: _response.data && _response.data.error ? _response.data.error : _message, type: 'warn', width: '10em' }) } reject(res) }) }) }
github地址:https://github.com/NoManReady/Tide/blob/master/src/utils/fetch.js
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com