微信小程序wx.request封装与刷新token

大致流程:
1、用户登录之后会返回两个token(access_token,refresh_token),请求数据时,请求头为access_token;
2、当返回值为code=103时(access_token过期时),通过接口(刷新token)api向后端获取新的access_token,请求参数为refresh_token;
3、拿到新的token(access_token,refresh_token)之后替换掉之前的token,重新请求数据接口;
4、如果请求(刷新token)api也过期,则跳到登录页

1、封装wx.request

在http文件夹下创建request.js
在这里插入图片描述
代码如下:

// 网络请求
// 获取数据
//获取数据状态:loading、toast
// 请求头处理(机型、大小、系统、屏幕)
let store = require("../utils/store.js")
let system = store.getSystemInfo()
const clienInfo = {
    "clientType": "mp",
    "appnm": "myApplet",
    "model": system.model,
    "os": system.system,
    "screen": system.screenWidth + "*" + system.screenHeight,
    "version": App.version,
    "chennel": "miniprogram"
}
module.exports = {
    fetch: (url, data = {}, option = {}) => {
        let { loading = true, toast = true, method = 'get' } = option
        return new Promise((resolve, reject) => {
            if (loading) {
                wx.showLoading({
                    title: '努力加载中...',
                    mask: true
                })
            }
            let env = App.config.baseApi;
            wx.request({
                url: env + url,
                data,
                method,
                header: {
                    "clienInfo": JSON.stringify(clienInfo),
                    "AUTHORIZATION": store.getItem("accescc_token")
                },
                success: function(result) {
                    let res = result.data
                    if (res.code == 200 || res.code == 10000) {
                        if (loading) {
                            wx.hideLoading();
                        }
                        resolve(res);
                    } else if (res.code == 103) {
                        wx.request({
                            url: env + "/index/Customer/refresh",
                            method: 'POST',
                            header: {
                                "clienInfo": JSON.stringify(clienInfo),
                                "AUTHORIZATION": store.getItem("refresh_token")
                            },
                            success: function(result) {
                                console.log('result', result.data.code)
                                if (result.data.code == 200) {
                                    wx.setStorageSync('accescc_token', result.data.data)
                                    wx.startPullDownRefresh()
                                    resolve(res)
                                } else if (result.data.code == 103) {
                                    wx.showToast({
                                        title: 'token失效,重新登录',
                                        icon: "none"
                                    })
                                    setTimeout(() => {
                                        wx.redirectTo({
                                            url: '/paegs/login/login',
                                        })
                                    }, 2000)
                                } else {
                                    wx.showToast({
                                        title: result.msg,
                                        icon: "none"
                                    })
                                }

                            }
                        })
                    } else {
                        if (toast) {
                            wx.showToast({
                                mask: true,
                                title: res.msg,
                                icon: 'none',
                                duration: 2000
                            })
                        } else {
                            wx.hideLoading();
                        }
                        resolve(res);
                    }
                },
                fail: function(result) {
                    
                }
            })
        })
    },
}

ps:使用wx.startPullDownRefresh(),需要在app.json配置"enablePullDownRefresh": true

2、在请求接口的页面监听用户下拉动作

onPullDownRefresh: function () {
	this.getList()//请求数据方法
  },

emmm,大概实现方法是这样想的了,如果有人有更好的实现方式,欢迎一起讨论(嘻嘻)

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
微信小程序中,可以使用wx.login方法获取登录凭证code,并将该code发送给服务器进行登录验证。服务器验证成功后,可以返回一个用户标识token或session_key等信息,用于保存登录态。 要保存登录态,可以使用小程序的本地存储功能。可以使用wx.setStorage方法将token或session_key等信息存储到本地,并在后续的请求中使用。 以下是一个简单的示例: ```javascript // 获取登录凭证code wx.login({ success: res => { const code = res.code; // 将code发送给服务器进行登录验证 // 服务器验证成功后返回token或session_key等信息 // 假设服务器返回的信息存在res.data中 // 保存token或session_key到本地存储 wx.setStorage({ key: 'token', data: res.data.token }); }, fail: err => { console.error(err); // 处理错误 } }); ``` 在上面的示例中,我们使用wx.login方法获取登录凭证code,并将该code发送给服务器进行登录验证。假设服务器返回的信息存在res.data中,我们使用wx.setStorage方法将token存储到本地。 在后续的请求中,可以使用wx.getStorage方法获取本地存储的token,并将其添加到请求的header中,或者根据具体需求进行处理。 ```javascript // 发起带有token的请求 wx.getStorage({ key: 'token', success: res => { const token = res.data; // 发起请求时添加token到header中 wx.request({ url: 'https://api.example.com/data', header: { 'Authorization': 'Bearer ' + token }, success: res => { console.log(res.data); // 处理数据 }, fail: err => { console.error(err); // 处理错误 } }); }, fail: err => { console.error(err); // 处理错误 } }); ``` 在上述示例中,我们使用wx.getStorage方法获取本地存储的token,并在请求中添加到header中。这样可以在后续的请求中带上登录态信息,进行权限验证或其他操作。 请注意,由于本地存储是在用户手机上进行,可能会存在一定的安全风险。所以,对于敏感信息,建议使用加密或其他安全机制进行保护。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值