微信小程序封裝網(wǎng)絡(luò)請求和攔截器實戰(zhàn)步驟
1. 前言
今天和合作伙伴對接代碼的時候,打開壓縮包,發(fā)現(xiàn)項目有很大的問題,項目里根本沒有登錄驗證請求封裝攔截器這些東西,在開發(fā)小程序時,無疑想要維護還是比較麻煩的,實際上我們通常需要封裝網(wǎng)絡(luò)請求和攔截器,以實現(xiàn)統(tǒng)一處理狀態(tài)碼和存儲用戶登錄信息等功能。這樣可以提高開發(fā)效率,減少代碼重復(fù),同時也可以提高代碼的可維護性和可讀性。
2. 思路
封裝網(wǎng)絡(luò)請求
首先,需要封裝網(wǎng)絡(luò)請求,負責(zé)發(fā)送請求和處理響應(yīng)。該類應(yīng)該包含以下方法:
·request(url, method, data, header):發(fā)送網(wǎng)絡(luò)請求,并返回響應(yīng)結(jié)果。
·get(url, data, header):發(fā)送 GET 請求。
·post(url, data, header):發(fā)送 POST 請求。
等不同請求方式
可以使用小程序提供的 wx.request 方法來實現(xiàn)網(wǎng)絡(luò)請求,該方法的參數(shù)與上述方法的參數(shù)一一對應(yīng)。在處理響應(yīng)時,可以使用Promise對象來處理異步操作。
統(tǒng)一處理狀態(tài)碼
可以創(chuàng)建一個checkStatus
函數(shù),用于統(tǒng)一處理狀態(tài)碼。該函數(shù)接受一個response參數(shù),用于判斷請求是否成功。如果請求成功,則返回一個Promise
對象,以便于我們進行后續(xù)的操作。如果請求失敗,則拋出一個錯誤。
創(chuàng)建 攔截器類
具體處理邏輯見下文。
2.1 封裝網(wǎng)絡(luò)請求
封裝一個request函數(shù),用于發(fā)送請求。該函數(shù)接受一個參數(shù)options,用于配置請求。我們可以在該函數(shù)中使用小程序提供的wx.request
接口發(fā)送請求,并在請求完成后返回一個Promise對象,以便于我們進行后續(xù)的操作。
function request(options) { return new Promise((resolve, reject) => { wx.request({ url: options.url, method: options.method || 'GET', data: options.data || {}, header: options.header || {}, success: resolve, fail: reject }) }) }
2.2 統(tǒng)一處理狀態(tài)碼
我們可以封裝一個checkStatus
函數(shù),用于統(tǒng)一處理狀態(tài)碼。該函數(shù)接受一個response參數(shù),用于判斷請求是否成功。如果請求成功,則返回一個Promise
對象,以便于我們進行后續(xù)的操作。如果請求失敗,則拋出一個錯誤。
function checkStatus(response) { const { statusCode, data } = response if (statusCode >= 200 && statusCode < 300) { return Promise.resolve(data) } else { const error = new Error(`請求失敗,狀態(tài)碼:${statusCode}`) error.response = response throw error } }
2.3 封裝攔截器
我們可以封裝一個interceptor
函數(shù),用于封裝攔截器。該函數(shù)接受一個chain參數(shù),用于執(zhí)行攔截器鏈。我們可以在該函數(shù)中定義一個requestInterceptor
和一個responseInterceptor
,用于分別處理請求和響應(yīng)的攔截器。我們可以在requestInterceptor
中設(shè)置請求頭,以便于在后續(xù)的請求中進行身份驗證。我們可以在responseInterceptor
中統(tǒng)一處理狀態(tài)碼,并在請求成功時更新用戶登錄信息。
function interceptor(chain) { const requestInterceptor = (options) => { // 設(shè)置請求頭 options.header.Authorization = 'Bearer ' + getApp().globalData.token return chain.request(options) } const responseInterceptor = (response) => { const { statusCode, data } = response if (statusCode >= 200 && statusCode < 300) { // 更新用戶登錄信息 getApp().globalData.userInfo = data.userInfo } else { const error = new Error(`請求失敗,狀態(tài)碼:${statusCode}`) error.response = response throw error } return response } return { request: requestInterceptor, response: responseInterceptor } }
2.4 不同請求方式兼容
//封裝put請求方式的代碼如下: function put(options) { return new Promise((resolve, reject) => { wx.request({ url: options.url, method: 'PUT', data: options.data || {}, header: options.header || {}, success: resolve, fail: reject }) }) } //封裝delete請求方式的代碼如下: function del(options) { return new Promise((resolve, reject) => { wx.request({ url: options.url, method: 'DELETE', data: options.data || {}, header: options.header || {}, success: resolve, fail: reject }) }) } //封裝post請求方式的代碼如下: function post(options) { return new Promise((resolve, reject) => { wx.request({ url: options.url, method: 'POST', data: options.data || {}, header: options.header || {}, success: resolve, fail: reject }) }) }
2.5 全局存儲用戶登錄信息
我們可以在小程序的app.js中定義一個全局變量globalData
,用于存儲用戶登錄信息。我們可以在登錄成功后將用戶信息保存到該變量中,并在后續(xù)的請求中使用該變量進行身份驗證。
App({ globalData: { userInfo: null, token: null } })
2.6 完整代碼
// request.js function request(options) { return new Promise((resolve, reject) => { wx.request({ url: options.url, method: options.method || 'GET', data: options.data || {}, header: options.header || {}, success: resolve, fail: reject }) }) } function put(options) { return new Promise((resolve, reject) => { wx.request({ url: options.url, method: 'PUT', data: options.data || {}, header: options.header || {}, success: resolve, fail: reject }) }) } function del(options) { return new Promise((resolve, reject) => { wx.request({ url: options.url, method: 'DELETE', data: options.data || {}, header: options.header || {}, success: resolve, fail: reject }) }) } function post(options) { return new Promise((resolve, reject) => { wx.request({ url: options.url, method: 'POST', data: options.data || {}, header: options.header || {}, success: resolve, fail: reject }) }) } function checkStatus(response) { const { statusCode, data } = response if (statusCode >= 200 && statusCode < 300) { return Promise.resolve(data) } else { const error = new Error(`請求失敗,狀態(tài)碼:${statusCode}`) error.response = response throw error } } function interceptor(chain) { const requestInterceptor = (options) => { options.header.Authorization = 'Bearer ' + getApp().globalData.token return chain.request(options) } const responseInterceptor = (response) => { const { statusCode, data } = response if (statusCode >= 200 && statusCode < 300) { getApp().globalData.userInfo = data.userInfo } else { const error = new Error(`請求失敗,狀態(tài)碼:${statusCode}`) error.response = response throw error } return response } return { request: requestInterceptor, response: responseInterceptor } } export { request, put, del, post, checkStatus, interceptor }
3. 使用示例
import { request, interceptor, checkStatus } from './request' const chain = interceptor({ request: (options) => { console.log('請求攔截器') return options }, response: (response) => { console.log('響應(yīng)攔截器') return response } }) request({ url: 'https://xxx.com/api/users', method: 'GET' }) .then(checkStatus) .then(data => { console.log(data) }) .catch(error => { console.log(error) })
4. 注意事項
① 在使用攔截器時,需要注意攔截器的執(zhí)行順序。在上述示例中,攔截器的執(zhí)行順序是先執(zhí)行請求攔截器,再執(zhí)行響應(yīng)攔截器。
② 在小程序中,我們可以使用getApp()函數(shù)來獲取小程序?qū)嵗?,從而訪問全局變量。
③ 在發(fā)送請求時,需要注意請求的參數(shù)配置。在上述示例中,默認(rèn)使用的是GET請求方法和空對象作為請求參數(shù),并且配置了常用請求方式,如果需要使用其他請求方法或者自定義請求參數(shù),請在調(diào)用request函數(shù)時進行相應(yīng)的配置。
5. 結(jié)語
實際上請求的url地址也可以單獨封裝的,需要單獨新建一個js文件里面導(dǎo)出域名或者url地址,再調(diào)用request封裝的地方,import引入一下就可以了,以上便是關(guān)于小程序封裝網(wǎng)絡(luò)請求和攔截器的全部內(nèi)容,希望可以幫到有需要的小伙伴。歡迎大家多多交流,共同進步~
到此這篇關(guān)于微信小程序封裝網(wǎng)絡(luò)請求和攔截器實戰(zhàn)步驟的文章就介紹到這了,更多相關(guān)小程序封裝網(wǎng)絡(luò)請求和攔截器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript中的垃圾回收與內(nèi)存泄漏示例詳解
這篇文章主要給大家介紹了關(guān)于JavaScript中垃圾回收與內(nèi)存泄漏的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用JavaScript具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05javascript window.onerror事件學(xué)習(xí)新收獲
javascript window.onerror事件學(xué)習(xí)新收獲...2007-11-11使用js實現(xiàn)將后臺傳入的json數(shù)據(jù)放在前臺顯示
今天小編就為大家分享一篇使用js實現(xiàn)將后臺傳入的json數(shù)據(jù)放在前臺顯示,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08