微信小程序wx.request拦截器使用详解
一.
请求后台的时候,服务端对每一个请求都会验证权限,而前端也需要对服务器返回的特殊状态码统一处理,所以可以针对业务封装请求。
首先我们通过request拦截器在每个请求头里面塞入token等信息,好让后端对请求进行权限验证。并创建一个respone拦截器,当服务端返回特殊的状态码,我们统一做处理,如未登录网络错误等操作。
二.
1.首先了解小程序官方api-wx.request(),通过示例可以看出wx.request的参数是一个对象,拥有传输地址,传输内容,响应头,成功失败回调函数等属性和方法,我们可以通过封装相应的响应头和成功失败回调函数达到相应的目的:
//官方代码示例
wx.request({
url:'test.php',//仅为示例,并非真实的接口地址
data:{
x:'',
y:''
},
header:{
'content-type':'application/json'//默认值
},
success(res){
console.log(res.data)
}
fail(res){
console.log(res)
}
})
2.封装
封装请求头和返回的状态码(注:具体头需要添加哪些属性,返回的状态码处理,是根据与后台实际沟通所需的参数来制定的)
constapp=getApp();
constappid='xxxx';
constappSecret='xxxxxx';
letajaxNum=0;
//获取accessToken
functiongetAccessToken(callback){
wx.request({
url:'/api/Token',
data:{
appid:aesEncrypt(appid),//aesEncrypt():自定义的用crypto-js.js进行aes加密的方法,这里只需要知道加密了即可,不需要关注此方法
appSecret:aesEncrypt(appSecret),
},
success:function(res){
if(res.statusCode===200&&res.data.code===0){
letaccesstoken=res.data.data.accesstoken;
if(typeof(callback)==='function'&&accesstoken){
callback(accesstoken);
}
}
},
})
}
//封装request请求
constmyRequest=options=>{
if(options){
getAccessToken(function(accesstoken){
//header设置Content-Type,accesstoken,usertoken,noncestr,timestamp等信息,与后台协商好
if(options.header===undefined||options.header===null){
options.header={};
}
options.header['Content-Type']='application/x-www-form-urlencoded;charset=UTF-8';
//usertoken在登录后保存在缓存中,所以从缓存中取出,放在header
letusertoken=wx.getStorageSync('usertoken');
if(usertoken){
options.header['usertoken']=usertoken;
}
//自定义getNoncestr()设置随机字符串,getTimestamp()获取时间戳
letnoncestr=getNoncestr();
lettimestamp=getTimestamp();
//sign进行加密
letsign=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
letbaseUrl=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){
letdataStr=JSON.stringify(options.data);
letbase64Str=base64Encrypt(dataStr);
options.data=serializeData({param:base64Str});
}
}
//success
if(options.success&&typeof(options.success)==='function'){
letsuccessCallback=options.success;
options.success=function(res){
//判断不同的返回码200/404
if(res.statusCode===200){
try{
//接收的后台数据用自定义base64解密方法解密后转为对象
letstr=base64Decrypt(res.data);
letdata=JSON.parse(str);
if(parseInt(data.resultCode,10)===-1){//后台商议好的状态码,-2未登录,-1-3后台出错
console.error('网络超时,请稍后重试');
}elseif(parseInt(data.resultCode,10)===-3){
console.error(data.msg);
}elseif(parseInt(data.resultCode,10)===-2){
console.log("用户未登录-ajax");
}
res.data=data;
//调用自定义的success
successCallback(res);
}catch(e){
console.error('出错了,'+e+',接口返回数据:'+res.data);
}
}elseif(res.statusCode===404){
console.log('404');
}
}
}
//执行微信的请求
wx.request(options);
});
}
}
module.exports={
myRequest:myRequest
页面调用示范(与wx.request传参一致):
constajax=require('ajax.js');
ajax.javaRequest({
url:'/xxx',
data:{
xxxx:xxx
},
method:'POST',
success:res=>{
console.log(res,'成功')
}
})
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。