Detailed explanation of uniapp painless token refresh method

Detailed explanation of uniapp painless token refresh method

When the front-end requests the interface, it is defined with the back-end. If the status code is 401, it means that the token has expired and the front-end needs to request a new token.

The general process is as follows:

1. After the user logs in, the backend will return two tokens, accessToken and refreshToken, which are stored in Storage

When requesting data, the request header uses accessToken to send the interface

2. When the token expires, we get a new token from the backend through the interface, and the request parameter is refreshToken

3. After we get the new accessToken and refreshToken, replace the token stored in the previous Storage

4. At the same time, we need to use the new accessToken to request the interface that reported 401 again, get the data, and achieve painless token refresh

5. If the new token returned by the backend cannot be used, it means that you need to log in again and jump to the login page (this step can be used flexibly. I personally use a routing plug-in: https://ext.dcloud.net.cn/plugin?id=578)

Use and implement with uni-app plugin:

Go to the uni-app plugin market to download the packaged request network request and configure it to your own project according to the document

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

After configuration, modify the index.js file in the vmeitime-http folder

Then modify the interface.js file in the vmeitime-http folder to expose the 401 status

If you still don't understand after reading this, please look at my source code. Please note that I used two plugins. Please understand and digest them carefully, and think about them in your own projects...

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

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

//...other logic code export const execute = (name, data = {}) => {

    //Set the pre-request interceptor http.interceptor.request = (config) => {
        let token = uni.getStorageSync('accessToken')
        delete config.header['x-access-token']
        if (token) {
            config.header['x-access-token'] = token
        }
    }
    //Set the interceptor after the request ends 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: 'Tips',
                        content: 'Your account is logged in from another location!',
                        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')
            }
        }
        // Unified processing of error requests 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
}
    // Refresh token method 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: 'Login expired, please log in again! ',
                icon: "none",
                success() {
                    Router.push({
                        name: 'login',
                        params: {
                            'RouterName': 'home'
                        }
                    })
                }
            });
        }
    }

The above is a detailed explanation of the uniapp painless token refresh method. For more information about the uni-app painless token refresh method, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • uniapp dynamic modification of element node style detailed explanation
  • Detailed explanation of the difference between uniapp and vue
  • Detailed explanation of uniapp's global variable implementation
  • Detailed explanation of styles in uni-app

<<:  Solution to the problem that VC6.0 cannot be used when installed on WIN10

>>:  Summary of MySQL slow log practice

Recommend

Advanced Usage Examples of mv Command in Linux

Preface The mv command is the abbreviation of mov...

Vue Virtual DOM Quick Start

Table of contents Virtual DOM What is virtual dom...

FastDFS and Nginx integration to achieve code analysis

FastDFS & Nginx Integration: The tracker is c...

Vue+echarts realizes stacked bar chart

This article shares the specific code of Vue+echa...

Vue's vue.$set() method source code case detailed explanation

In the process of using Vue to develop projects, ...

Solution to no Chinese input method in Ubuntu

There is no solution for Chinese input method und...

Method of building docker private warehouse based on Harbor

Table of contents 1. Introduction to Harbor 1. Ha...

How to import txt into mysql in Linux

Preface When I was writing a small project yester...

How does Vue solve the cross-domain problem of axios request front end

Table of contents Preface 1. Why do cross-domain ...

CSS float property diagram float property details

Using the CSS float property correctly can become...