微信小程序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.封装
封装请求头和返回的状态码(注:具体头需要添加哪些属性,返回的状态码处理,是根据与后台实际沟通所需的参数来制定的)
const app = getApp(); const appid = 'xxxx'; const appSecret = 'xxxxxx'; letajaxNum = 0; // 获取accessToken function getAccessToken(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) { let accesstoken = res.data.data.accesstoken; if (typeof (callback) === 'function' && accesstoken) { callback(accesstoken); } } }, }) }// 封装request请求 const myRequest = 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 let usertoken = wx.getStorageSync('usertoken'); if (usertoken) { options.header['usertoken'] = usertoken; } // 自定义getNoncestr()设置随机字符串,getTimestamp()获取时间戳 let noncestr = getNoncestr(); let timestamp = getTimestamp(); // sign进行加密 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 = https://www.it610.com/article/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 { // 接收的后台数据用自定义base64解密方法解密后转为对象 let str = base64Decrypt(res.data); let data = https://www.it610.com/article/JSON.parse(str); if (parseInt(data.resultCode, 10) === -1) {//后台商议好的状态码,-2未登录,-1-3后台出错 console.error('网络超时,请稍后重试'); } else if (parseInt(data.resultCode, 10) === -3) { console.error(data.msg); } else if (parseInt(data.resultCode, 10) === -2){ console.log("用户未登录-ajax"); } res.data = https://www.it610.com/article/data; //调用自定义的success successCallback(res); } catch (e) { console.error('出错了,' + e + ',接口返回数据:' + res.data); } } else if(res.statusCode === 404) { console.log('404'); } } } //执行微信的请求 wx.request(options); }); } }module.exports = { myRequest: myRequest }

【微信小程序wx.request拦截器】页面调用示范(与wx.request传参一致):
const ajax = require('ajax.js'); ajax.javaRequest({ url: '/xxx', data: { xxxx: xxx }, method: 'POST', success: res => { console.log(res, '成功') } })

    推荐阅读