2019-09-09 15:39:57 4595瀏覽
今天千鋒扣丁學(xué)堂HTML5培訓(xùn)老師給大家分享一篇關(guān)于微信小程序HTTP請(qǐng)求從0到1封裝的詳細(xì)介紹,首先作為一個(gè)前端開(kāi)發(fā)者,從最開(kāi)始的js、jQuery一把梭,后來(lái)的vue、react、angular等MVVM、MVC框架,我們?cè)陂_(kāi)發(fā)工程中都離不開(kāi)HTTP庫(kù)的使用。
wx.request({ url: 'test.php', //僅為示例,并非真實(shí)的接口地址 data: { x: '', y: '' }, header: { 'content-type': 'application/json' // 默認(rèn)值 }, success (res) { console.log(res.data) } })
class Axios { constructor() { this.instance = null // 類(lèi)的實(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 } }
const axios = Axios.getInstance()
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(options) { const { config } = this // 實(shí)例請(qǐng)求的時(shí)候添加基本配置 const requsetOptions = { ...config, ...options } return dispatchRequest(requsetOptions) }
const instance = (config = {}) => { return axios.create({ base: globalApi, ...config }) }
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() } }) } }
class InterceptorManager { constructor() { this.fulfilled = null this.rejected = null } use(fulfilled, rejected) { this.fulfilled = fulfilled this.rejected = rejected } }
constructor() { this.instance = null // 類(lèi)的實(shí)例 this.config = defaultConfig this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() } }
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 }
axios.interceptors.request.use( request => { return request }, err => { console.error(err) } )
axios.interceptors.response.use( response => { return response }, err => { console.error(err) } )
【關(guān)注微信公眾號(hào)獲取更多學(xué)習(xí)資料】 【掃碼進(jìn)入HTML5前端開(kāi)發(fā)VIP免費(fèi)公開(kāi)課】
查看更多關(guān)于“HTML5開(kāi)發(fā)技術(shù)資訊”的相關(guān)文章>>