微信小程序HTTP請求從0到1封裝
前言
作為一個前端開發(fā)者,從最開始的js、jQuery一把梭,后來的vue、react、angular等MVVM、MVC框架,我們在開發(fā)工程中都離不開HTTP庫的使用。
HTTP庫
1、jQuery的$.ajax
調(diào)用了XMLHttpRequest對象,封裝在相關(guān)函數(shù)在配置項中,一旦傳入了必需選項,則直接調(diào)用相應(yīng)的send()方法進行數(shù)據(jù)的請求
2、Axios
基于Promise的請求庫,通過判斷XMLHTTPRequest對象存在與否,來支持客戶端和node服務(wù)端發(fā)送請求,封裝的很不錯的HTTP庫,支持promise、攔截請求和響應(yīng)等
小程序網(wǎng)絡(luò)請求
wx.request({ url: 'test.php', //僅為示例,并非真實的接口地址 data: { x: '', y: '' }, header: { 'content-type': 'application/json' // 默認(rèn)值 }, success (res) { console.log(res.data) } })
小程序本身的請求已經(jīng)封裝的很不錯了,使用起來和$.ajax相似,支持許多配置項的設(shè)置,但是缺少公共配置、響應(yīng)和請求攔截等實用功能
第一步--創(chuàng)建請求實例
class Axios { constructor() { this.instance = null // 類的實例 this.config = defaultConfig } create(instanceConfig) { const { config } = this // 創(chuàng)建實例的時候添加基本配置 this.config = { ...config, ...instanceConfig } return this } // 單例 static getInstance() { if (!this.instance) { this.instance = new Axios() } return this.instance } }
創(chuàng)建實例
const axios = Axios.getInstance()
promise包裝小程序請求
const dispatchRequest = function(config) { return new Promise((resolve, reject) => { wx.request({ ...config, url: config.base + config.url, success: res => { resolve(res) }, fail: res => { reject(res) } }) }) }
給請求實例添加request方法
request(options) { const { config } = this // 實例請求的時候添加基本配置 const requsetOptions = { ...config, ...options } return dispatchRequest(requsetOptions) }
第二步--創(chuàng)建請求工具方法
創(chuàng)建實例,通過create設(shè)置基本配置項
const instance = (config = {}) => { return axios.create({ base: globalApi, ...config }) }
創(chuàng)建請求工具方法,執(zhí)行實例request
export function request(options) { const { baseConfig, url, method, data, isLogin } = options instance(baseConfig) .request({ url, method: method || 'GET', data }) .then(res => { options.success && options.success(res) }) .catch(err => { if (options.error) { options.error(err) } else { errAlert() } }) } }
這樣,一個請求的工具方法就完成了,但是這個方法現(xiàn)在只支持基本的請求和基本配置項的配置,還是缺少我們很常用的公共請求和響應(yīng)的攔截。
第三部--添加請求和響應(yīng)的攔截器
創(chuàng)建攔截器實例
class InterceptorManager { constructor() { this.fulfilled = null this.rejected = null } use(fulfilled, rejected) { this.fulfilled = fulfilled this.rejected = rejected } }
在請求實例的構(gòu)造方法中添加請求和響應(yīng)攔截實例
constructor() { this.instance = null // 類的實例 this.config = defaultConfig this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() } }
在實例的request添加promise執(zhí)行隊列
request(options) { const { config, interceptors } = this // 實例請求的時候添加基本配置 const requsetOptions = { ...config, ...options } const promiseArr = [] // promise存儲隊列 // 請求攔截器 promiseArr.push({ fulfilled: interceptors.request.fulfilled, rejected: interceptors.request.rejected }) // 請求 promiseArr.push({ fulfilled: dispatchRequest, rejected: null }) // 回調(diào)攔截器 promiseArr.push({ fulfilled: interceptors.response.fulfilled, rejected: interceptors.response.rejected }) let p = Promise.resolve(requsetOptions) promiseArr.forEach(ele => { p = p.then(ele['fulfilled'], ele['rejected']) }) return p }
在請求工具方法中通過設(shè)置請求和響應(yīng)的攔截方法
axios.interceptors.request.use( request => { return request }, err => { console.error(err) } )
axios.interceptors.response.use( response => { return response }, err => { console.error(err) } )
在請求攔截方法里面可以添加數(shù)據(jù)轉(zhuǎn)換,在請求頭部添加sign、token等,在響應(yīng)攔截方法里面去做公共的數(shù)據(jù)處理等
最后
從零搭建一個簡單的請求庫很簡單,但是想考慮的方方面面,設(shè)計好整個流程會比較麻煩,需要不斷的改進和重構(gòu),本文的搭架過程參考了Axios的部分源碼。
好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。
相關(guān)文章
JavaScript獲得url所有參數(shù)鍵值表的方法
這篇文章主要介紹了JavaScript獲得url所有參數(shù)鍵值表的方法,實例分析了javascript操作URL的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03javascript實現(xiàn)獲取指定精度的上傳文件的大小簡單實例
下面小編就為大家?guī)硪黄猨avascript實現(xiàn)獲取指定精度的上傳文件的大小簡單實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-10-10JS輕松實現(xiàn)CSS設(shè)置,DIV+CSS常用CSS設(shè)置
JS輕松實現(xiàn)CSS設(shè)置,DIV+CSS常用CSS設(shè)置...2007-02-02小程序?qū)崿F(xiàn)新用戶判斷并跳轉(zhuǎn)激活的方法
這篇文章主要介紹了小程序?qū)崿F(xiàn)新用戶判斷并跳轉(zhuǎn)激活的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05