小程序wxRequest封装一个无痛刷新token方法?

小程序 文章 2022-03-31 09:20 939 0 全屏看文

AI助手支持GPT4.0

小程序wxRequest封装一个无痛刷新token方法?The applet wxRequest encapsulates a painless token refresh method?

小程序wxRequest封装一个无痛刷新token方法?

当token过期后就去获取新的token,但要阻止同一个页面多个异步请求,在请求到新的token前,把请求任务放在队列,新token生成后再执行任务队列的请求,大概咋写啊,我怎么写都不对,就是怎么回调任务队列的请求

When the token expires, get a new token, but block multiple asynchronous requests on the same page. Before requesting a new token, put the request task in the queue, and execute the request of the task queue after the new token is generated. I don't know how to write it, that is, how to call back the request of the task queue

回答:

那一抹笑😃 穿透阳光:

wx.pro.request = (options) => {

 return new Promise((resolve, reject) => {

let req = {

     url: wx.getStorageSync("serverurl"+ options.url,

        method: options.method || 'GET',

       header: {Authorization: 'Bearer ' + wx.getStorageSync("token")},

       success: (res) => {

         if (res.statusCode == 401 && requestNumber <= 3{

             login().then((log) => {

                requestNumber++;

                    if (log.results{wx.setStorageSync("token", log.results.token); }

                    resolve(wx.pro.request(options))

              })

         } else {

             resolve(getData(res))

          },

     fail: (err) => {

        reject(getData(err));

      }

  };

 if (options.data{

    req.data = options.data;

    req.header['content-type'= 'application/json';

    }

   wx.request(req);

 });

};

那一抹笑😃 穿透阳光:let requestNumber = 0; //登录接口请求次数,防止接口报错,无限请求

function login() {
    return wx.pro.login().then((res) => {
        return wx.pro.request({
            method: 'GET',
            url: 'api/miniprogram/auth',
            data: {
                code: res.code
            },
            header: {
                'content-type': 'application/json';
            },
        })
    })
}
拾忆:

token刷新要放在服务端处理不是放在小程序端处理。

服务端定期刷新token放在数据库或者redis供小程序使用。

-EOF-

AI助手支持GPT4.0