微信小程序request请求封装, token失效刷新继续请求

let isRefreshing = true; // 请求锁
let pendings = []; // 请求列表
const pathArr = ['pages/buy-goods/index']; // 不需要登录的路径
function ajax(method, url, data, options = {
  needLogin: true
}) {
  const app = getApp();
  const apiUrl = app.globalData.url;
  const token = wx.getStorageSync("token");
  const time = new Date(wx.getStorageSync("expiredAt")).getTime(); //过期时间
  const newTime = Date.parse(new Date()); // 当前时间
  const pages = getCurrentPages();
  const router = pages[pages.length - 1]['route']; // 当前路由
  if(pathArr.includes(router)) options.needLogin = false; // 当前路径是否需要登录
  return new Promise((resolve, reject) => {

    // 需要登录 但是 token不存在 跳转登录
    if(!token && options.needLogin) {
      wx.redirectTo({
        url: '/pages/login/index',
      })
      return
    }

    // 判断token过期
    if (token && newTime - time > 0) { 
      if(isRefreshing) {
        updateToken();
        isRefreshing = false;
        pendings.push(() => {
          resolve(ajax(method, url, data, options))
        })
      }
    }

    // 请求主体
    wx.request({
      url: apiUrl + url,
      header: {
        Authorization: token ? wx.getStorageSync("token") : '',
        "content-type":  options.type ? options.type : 'application/json'
      },
      method,
      data,
      dataType: 'json',
      success(res) {
        wx.hideLoading();
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        if (res.data.success_code == 200) {
          resolve(res.data)
        } else if(res.data.error_code === 401 || res.data.error_code === 402) {
          if(isRefreshing) {
            updateToken();
            isRefreshing = false;
            pendings.push(() => {
              resolve(ajax(method, url, data, options))
            })
          }
        } else if(res.data.error_code === 900) { // 快递下单超区
          resolve(res.data);
        } else {
          reject(res.data.error_message || res.data.message);
        }
      },
      fail() {
        wx.showToast({
          title: '请求发送失败',
          icon: "none"
        })
      }
    })
  })
}
// 刷新token
function updateToken() {
  const app = getApp();
  const apiUrl = app.globalData.url;
  const userId = wx.getStorageSync("userId");
  const token = wx.getStorageSync("token");
  wx.request({
    url: apiUrl + '/api/transfer/token/' + userId,
    header: {
      "Authorization": token,
    },
    method: "GET",
    dataType: "json",
    success(res) {
      if (res.data.success_code == 200) {
        wx.setStorageSync("expiredAt", res.data.data.expired.replace(/\.|\-/g, '/'));
        wx.setStorageSync("token", res.data.data.token);
        pendings.map((callback) => {
          callback();
        })
        isRefreshing = true;
      } else {
        toLogin();
      }
    }
  })
}
// 前往登录页面 清空状态
function toLogin() {
  wx.showToast({
    title: '登录失效,请重新登录',
    icon: "none",
    success: () => {
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/login/index',
        })
        pendings = [];
        isRefreshing = true;
      }, 1200);
    }
  })
}
module.exports = {
  ajax
};

 

你可能感兴趣的:(微信小程序)