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