溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

uniapp無痛刷新token的方法介紹

發(fā)布時(shí)間:2021-06-04 16:22:43 來源:億速云 閱讀:834 作者:栢白 欄目:開發(fā)技術(shù)

本篇文章和大家了解一下uniapp無痛刷新token的方法介紹。有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)大家有所幫助。

前端在請(qǐng)求接口時(shí),和后端定義好了,如果狀態(tài)碼為 401 ,則表明 token 過期,需要前端請(qǐng)求新的 token

大概流程如下:

1.用戶登錄之后,后端會(huì)返回兩個(gè) token ,分別為accessToken 和refreshToken 存儲(chǔ)到Storage

平時(shí)請(qǐng)求數(shù)據(jù)時(shí),請(qǐng)求頭使用accessToken 來發(fā)送接口

2.當(dāng)返回401 token 過期后, 我們通過接口向后端獲取新的 token ,請(qǐng)求參數(shù)為refreshToken

3.我們拿到新的accessToken 和refreshToken 之后, 替換掉之前的Storage 中存儲(chǔ)的 token

4.同時(shí)還要將我們報(bào) 401 的哪個(gè)接口 ,使用新的accessToken ,重新請(qǐng)求一次, 拿到數(shù)據(jù),實(shí)現(xiàn)無痛刷新 token

5.如果后端返回的新的 token 也無法使用,表明需要重新登錄,跳到登錄頁(yè)(這一步可以靈活使用,我個(gè)人用的是一個(gè)路由插件配合使用的: https://ext.dcloud.net.cn/plugin?id=578)

配合uni-app的插件進(jìn)行使用和實(shí)現(xiàn):

到uni-app的插件市場(chǎng)下載封裝的request網(wǎng)絡(luò)請(qǐng)求,按照文檔配置到自己的項(xiàng)目上

地址:https://ext.dcloud.net.cn/plugin?id=159

配置好后修改vmeitime-http 文件夾下的 index.js 文件

uniapp無痛刷新token的方法介紹

uniapp無痛刷新token的方法介紹

再修改vmeitime-http 文件夾下的 interface.js 文件,將401狀態(tài)暴漏出來

uniapp無痛刷新token的方法介紹

如果看到這里還是看不明白,那么請(qǐng)看我的源碼,請(qǐng)注意我使用了兩個(gè)插件,觀眾們酌情理解,仔細(xì)消化,配合到自己的項(xiàng)目中思考...

import http from './interface'
import config from './config'

// request.js
import Vue from 'vue'
import Router  from '@/router'

//...其它邏輯代碼

export const execute = (name, data = {}) => {

    //設(shè)置請(qǐng)求前攔截器
    http.interceptor.request = (config) => {
        let token = uni.getStorageSync('accessToken')
        delete config.header['x-access-token']
        if (token) {
            config.header['x-access-token'] = token
        }
    }
    //設(shè)置請(qǐng)求結(jié)束后攔截器
    http.interceptor.response = async (response) => {
        const statusCode = response.statusCode;
        if (statusCode === 401) {
            response = await doRequest(response)
        }
        if (statusCode === 402) {
            uni.removeStorageSync('accessToken');
            uni.removeStorageSync('refreshToken');
            uni.removeStorageSync('realname');
            let jump = uni.getStorageSync('jump')
            if (!jump) {
                setTimeout(() => {
                    uni.showModal({
                        title: '提示',
                        content: '您的賬號(hào)在其它地點(diǎn)登錄!',
                        showCancel: false,
                        success: function(res) {
                            if (res.confirm) {
                                Router.push({
                                    name: 'login',
                                    params: {
                                        'RouterName': 'home'
                                    }
                                })
                            }
                        },
                    })
                });
                uni.setStorageSync('jump', 'true')
            }
        }
        if (statusCode == 403) {
            let jump = uni.getStorageSync('jump')
            if (!jump) {
                setTimeout(() => {
                    Router.replace({
                        name: 'login',
                        params: {
                            'RouterName': 'home'
                        }
                    })
                },500)
                uni.setStorageSync('jump', 'true')
            }
        }
        // 統(tǒng)一處理錯(cuò)誤請(qǐng)求
        const code = response.data.code;
        const message = response.data.message;
        if (response.statusCode == 200 && code !== 0 && code != -1 && code) {
            uni.showToast({
                title: message,
                icon: "none",
                duration: 2000
            });
        }
        return response;
    }
    return http.request({
        name: name,
        baseUrl: config.base,
        url: config.interface[name].path,
        method: config.interface[name].method ? config.interface[name].method : 'GET',
        dataType: 'json',
        data,
    })
}

export default {
    execute
}
    // 刷新 token 方法
    async function doRequest(response) {
        const res = await execute('refresh', {refreshToken: uni.getStorageSync('refreshToken')})
        const {
            code,
            data
        } = res.data
        if (code == 0) {
            uni.setStorageSync('accessToken', data.accessToken)
            uni.setStorageSync('refreshToken', data.refreshToken)
            let config = response.config
            config.header['x-access-token'] = data.accessToken
            const resold = await execute(config.name,{ ...config.data
            })
            return resold
        } else {
            uni.removeStorageSync('accessToken');
            uni.removeStorageSync('refreshToken');
            uni.showToast({
                title: '登陸過期請(qǐng)重新登陸!',
                icon: "none",
                success() {
                    Router.push({
                        name: 'login',
                        params: {
                            'RouterName': 'home'
                        }
                    })
                }
            });
        }
    }

以上就是uniapp無痛刷新token的方法的簡(jiǎn)略介紹,當(dāng)然詳細(xì)使用上面的不同還得要大家自己使用過才領(lǐng)會(huì)。如果想了解更多,歡迎關(guān)注億速云行業(yè)資訊頻道哦!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI