微信小程序wx.request攔截器使用詳解
一.
請(qǐng)求后臺(tái)的時(shí)候,服務(wù)端對(duì)每一個(gè)請(qǐng)求都會(huì)驗(yàn)證權(quán)限,而前端也需要對(duì)服務(wù)器返回的特殊狀態(tài)碼統(tǒng)一處理,所以可以針對(duì)業(yè)務(wù)封裝請(qǐng)求。
首先我們通過request攔截器在每個(gè)請(qǐng)求頭里面塞入token等信息,好讓后端對(duì)請(qǐng)求進(jìn)行權(quán)限驗(yàn)證。并創(chuàng)建一個(gè)respone攔截器,當(dāng)服務(wù)端返回特殊的狀態(tài)碼,我們統(tǒng)一做處理,如未登錄網(wǎng)絡(luò)錯(cuò)誤等操作。
二.
1.首先了解小程序官方api-wx.request() ,通過示例可以看出wx.request的參數(shù)是一個(gè)對(duì)象,擁有傳輸?shù)刂?,傳輸?nèi)容,響應(yīng)頭,成功失敗回調(diào)函數(shù)等屬性和方法,我們可以通過封裝相應(yīng)的響應(yīng)頭和成功失敗回調(diào)函數(shù)達(dá)到相應(yīng)的目的:
// 官方代碼示例
wx.request({
url: 'test.php', //僅為示例,并非真實(shí)的接口地址
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json' // 默認(rèn)值
},
success (res) {
console.log(res.data)
}
fail(res){
console.log(res)
}
})
2.封裝
封裝請(qǐng)求頭和返回的狀態(tài)碼(注:具體頭需要添加哪些屬性,返回的狀態(tài)碼處理,是根據(jù)與后臺(tái)實(shí)際溝通所需的參數(shù)來制定的)
const app = getApp();
const appid = 'xxxx';
const appSecret = 'xxxxxx';
let ajaxNum = 0;
// 獲取accessToken
function getAccessToken(callback) {
wx.request({
url: '/api/Token',
data: {
appid: aesEncrypt(appid),// aesEncrypt():自定義的用crypto-js.js進(jìn)行aes加密的方法,這里只需要知道加密了即可,不需要關(guān)注此方法
appSecret: aesEncrypt(appSecret),
},
success: function (res) {
if(res.statusCode ===200 && res.data.code === 0) {
let accesstoken = res.data.data.accesstoken;
if (typeof (callback) === 'function' && accesstoken) {
callback(accesstoken);
}
}
},
})
}
// 封裝request請(qǐng)求
const myRequest = options => {
if(options) {
getAccessToken(function (accesstoken){
// header 設(shè)置Content-Type,accesstoken, usertoken, noncestr, timestamp等信息,與后臺(tái)協(xié)商好
if(options.header === undefined || options.header === null) {
options.header = {};
}
options.header['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
// usertoken在登錄后保存在緩存中,所以從緩存中取出,放在header
let usertoken = wx.getStorageSync('usertoken');
if (usertoken) {
options.header['usertoken'] = usertoken;
}
// 自定義getNoncestr()設(shè)置隨機(jī)字符串,getTimestamp()獲取時(shí)間戳
let noncestr = getNoncestr();
let timestamp = getTimestamp();
// sign進(jìn)行加密
let sign = getSign(accesstoken, appid, appSecret, noncestr, timestamp);
if (timestamp) {
options.header['timestamp'] = timestamp;
}
if (noncestr) {
options.header['noncestr'] = noncestr;
}
if (sign) {
options.header['sign'] = sign;
}
//url
let baseUrl = config.BASE_HOST;
if (options.url.indexOf('http') != 0) {
options.url = baseUrl + options.url;
}
// method、data
if (options.method === undefined || options.method === null) {
options.method = 'post';
}
if (options.method.toLowerCase() === 'post') {
if(options.data) {
let dataStr = JSON.stringify(options.data);
let base64Str = base64Encrypt(dataStr);
options.data = serializeData({ param: base64Str });
}
}
//success
if (options.success && typeof(options.success) === 'function') {
let successCallback = options.success;
options.success = function(res) {
// 判斷不同的返回碼 200/404
if (res.statusCode === 200) {
try {
// 接收的后臺(tái)數(shù)據(jù)用自定義base64解密方法解密后轉(zhuǎn)為對(duì)象
let str = base64Decrypt(res.data);
let data = JSON.parse(str);
if (parseInt(data.resultCode, 10) === -1) {//后臺(tái)商議好的狀態(tài)碼,-2未登錄,-1-3后臺(tái)出錯(cuò)
console.error('網(wǎng)絡(luò)超時(shí),請(qǐng)稍后重試');
} else if (parseInt(data.resultCode, 10) === -3) {
console.error(data.msg);
} else if (parseInt(data.resultCode, 10) === -2){
console.log("用戶未登錄-ajax");
}
res.data = data;
//調(diào)用自定義的success
successCallback(res);
} catch (e) {
console.error('出錯(cuò)了,' + e + ',接口返回?cái)?shù)據(jù):' + res.data);
}
} else if(res.statusCode === 404) {
console.log('404');
}
}
}
//執(zhí)行微信的請(qǐng)求
wx.request(options);
});
}
}
module.exports = {
myRequest: myRequest
頁(yè)面調(diào)用示范(與wx.request傳參一致):
const ajax = require('ajax.js');
ajax.javaRequest({
url: '/xxx',
data: {
xxxx: xxx
},
method: 'POST',
success: res => {
console.log(res, '成功')
}
})
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript Window窗口對(duì)象屬性和使用方法
這篇文章主要介紹了JavaScript Window窗口對(duì)象屬性和使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01
JS簡(jiǎn)單獲取及顯示當(dāng)前時(shí)間的方法
這篇文章主要介紹了JS簡(jiǎn)單獲取及顯示當(dāng)前時(shí)間的方法,涉及javascript針對(duì)日期與時(shí)間的獲取與運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2016-08-08
淺談JavaScript的push(),pop(),concat()方法
下面小編就為大家?guī)硪黄獪\談JavaScript的push(),pop(),concat()方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-06-06
在JavaScript里防止事件函數(shù)高頻觸發(fā)和高頻調(diào)用的方法
這篇文章主要介紹了在JavaScript里防止事件函數(shù)高頻觸發(fā)和高頻調(diào)用的方法,本文方法從Underscore.js中摘錄而來,需要的朋友可以參考下2014-09-09
XHTML-Strict 內(nèi)允許出現(xiàn)的標(biāo)簽
XHTML-Strict 內(nèi)允許出現(xiàn)的標(biāo)簽...2006-12-12
JavaScript實(shí)現(xiàn)10秒后再次獲取驗(yàn)證碼
這篇文章主要為大家詳細(xì)介紹了JavaScript實(shí)現(xiàn)10秒后再次獲取驗(yàn)證碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12

