[WeChat Mini Program] Configure the token as a global variable and use a timer to detect token expiration

In the WeChat applet, you can configure the token as a global variable, and use a timer to detect whether the token expires. Set it to null when the token expires.

First, define a global variable token in the app.js file, and set the initial value to null, for example:

App({
    
    
  globalData: {
    
    
    token: null
  },
  // 其他代码...
})

Next, in the function of obtaining the token, set the obtained token as a global variable, and start a timer to detect whether the token expires. Set it to null when the token expires. The sample code is as follows:

App({
    
    
  globalData: {
    
    
    token: null
  },
  getToken: function() {
    
    
    // 发送异步请求获取 token
    wx.request({
    
    
      url: 'https://api.example.com/token', // 获取 token 的接口地址
      method: 'GET',
      success: (res) => {
    
    
        // 获取成功,将 token 设置为全局变量
        this.globalData.token = res.data.token;
        
        // 设置定时器,当 token 过期后将其设置为 null
        const expireTime = res.data.expireTime; // token 过期时间
        const currentTime = new Date().getTime(); // 当前时间
        const remainingTime = expireTime - currentTime; // 剩余时间
        setTimeout(() => {
    
    
          this.globalData.token = null;
        }, remainingTime);
      },
      fail: (err) => {
    
    
        // 获取失败,处理错误信息
        console.error(err);
      }
    });
  },
  // 其他代码...
})

In the above code, getTokenthe function is used to get the token and set it as a global variable. Then, use a timer to calculate the remaining time of the token, and set the token to null when the remaining time is over.

You can access the global variable token through in the page that needs to use the token getApp().globalData.token.

Please make corresponding modifications according to actual needs and the data structure returned by the interface.

Guess you like

Origin blog.csdn.net/gao511147456/article/details/131632090