乐趣区

关于小程序:小程序无痛刷新token

// 封装一个 http 办法

let temp_request = [], is_freshing = false;
/**
 * @param {string} url 
 * @param {string} method 
 * @param {Object} data 
 * @param {Boolean} loading 
 */
const http = function(url, method, data, loading) {
    let params_ = arguments
    return new Promise((resolve, reject) => {if(loading) {
            uni.showToast({
                title: '加载中',
                icon: 'loading',
                duration: 10000,
                // mask: true
            })
        }
        data.token = uni.getStorageSync('api_token')

        uni.request({
            url: url,
            method,
            data,
            success(res) {if(loading){
                    uni.hideToast({
                        title: '加载中',
                        icon: 'loading',
                        duration: 10000,
                    })
                }
                let code = res.data.code
                switch (code) {case 0: resolve(res.data.data);break;
                    case 200: 
                        // other handlers
                        break
                    case 401:
                        // token 过期
                        if(!is_freshing) {refresh()
                        }
                        // 关键步骤~~~~
                        resolve(new Promise(reslove => {temp_request.push(() => {reslove(request(...params_))
                            })
                        }))
                        break;
                    default: 
                        reject(res.data.data)
                }
            },
            fail(error) {reject(error.data.data)
            },
            complete(res) {}})
    })
}

function refresh() {
    is_freshing = true
    // 这里用的 uni-app 获取微信 code,原生微信小程序 wx.login()
    uni.login({
        provider: 'weixin',
        success: function (loginRes) {http('/mob/auth/login/miniProgram', 'post', {code}, true)
            .then((res) => {uni.setStorageSync('api_token', res.token)
                is_freshing = false
                temp_request.map(cb => cb())
                // 清空 temp_request
                temp_request = []})
            .catch((res) => {uni.hideLoading();
            })
        }
    });
    }, 1500)
}
export default http



//  测试

onShow() {
    // 在 token 过期的状况下,派发三个须要 token 的申请
    http({url1, 'get'})
    .then((res) => {console.log(res)
    })
    http({url1, 'get'})
    .then((res) => {console.log(res)
    })
    http({url1, 'get'})
    .then((res) => {console.log(res)
    })
}
退出移动版