1. Wx. login Refreshes the encapsulation of session_key and token
requestUtil.js
// Wechat login ————code
function loginCode () {
wx.showLoading();
return new Promise((resolve, reject) = > {
wx.login({
success: res1= > {
// Send res.code to the backend for openId, sessionKey, unionId
wx.request({
url: "url".data: { code: res1.code },
method: "GET".header: { 'Content-Type': 'application/json' },
success: function (res) {
switch (res.statusCode) {// (according to the actual situation)
case 200:
wx.setStorageSync('access_token', res.data.result);// Store the token locally
resolve({ status: 200 });
break;
default:
resolve({ status: res.statusCode }); }},fail: function (err) {
wx.showToast({ title: "System busy!".icon: 'error'}); reject(); }})},fail: function (err) {
wx.showToast({ title: "System busy!".icon: 'error'}); reject(); }})}); }module.exports = {
loginCode: loginCode,
}
Copy the code
2. Wx. request encapsulation
request.js
import { loginCode } from './requestUtil'
const app = getApp();
let requestArr = [], isRefreshing = false;// Request queue, whether token is being refreshed
// 401 Refresh the token
function refreshToken (obj, method, content_type, resolve) {
requestArr.push(() = > { resolve(httpRequest(obj, method, content_type)) });// Cache requests to the queue
if(! isRefreshing) { isRefreshing =true;
loginCode().then(res= > {
switch (res.status) {// (according to the actual situation)
case 200:
// re-request the queue
requestArr.map(MT= > { MT(); });
requestArr = [];// Clear the queue
break;
default:
wx.showToast({ title: "System busy!".icon: 'error' });
}
}).finally(() = > {
// Unrefresh
isRefreshing = false; wx.hideLoading(); }); }}function httpRequest (obj, method, content_type = 'application/json') {
return new Promise((resolve, reject) = > {
let token = wx.getStorageSync('access_token');// Obtain the local token
wx.request({
url: obj.url,
data: obj.data,
method: method,
header: { 'content-Type': content_type, 'token': token, },
success: (res) = > {
switch (res.statusCode) {// (according to the actual situation)
case 200:
resolve(res.data);
break;
case 401:// The token expires. Refresh the token based on the actual situation.
refreshToken(obj, method, content_type, resolve);
break;
default:
wx.showToast({ title: "System busy!".icon: 'error'}); reject(); }},fail: function (err) {
wx.showToast({ title: "System busy!".icon: 'error'}); reject(err); }}); })}function _get (obj) {
return httpRequest(obj, 'GET'.'application/json');
}
function _post (obj) {
return httpRequest(obj, 'POST'.'application/json');
}
function _put (obj) {
return httpRequest(obj, 'PUT'.'application/json');
}
function _delete (obj) {
return httpRequest(obj, 'DELETE'.'application/json');
}
module.exports = {
getAction: _get,
postAction: _post,
putAction: _put,
deleteAction: _delete,
}
Copy the code