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

Example test MySQL enum type

When developing a project, you will often encount...

Detailed explanation of Vue filter implementation and application scenarios

1. Brief Introduction Vue.js allows you to define...

MySQL and sqlyog installation tutorial with pictures and text

1. MySQL 1.1 MySQL installation mysql-5.5.27-winx...

How to generate Hive table creation statement comment script in MySQL metadata

Preface This article mainly introduces the releva...

Mount the disk in a directory under Ubuntu 18.04

Introduction This article records how to mount a ...

Docker setting windows storage path operation

When installing Docker on Windows 10, after selec...

Vue imitates ElementUI's form example code

Implementation requirements The form imitating El...

Implementing carousel effects with JavaScript

This article shares the specific code for JavaScr...

Detailed explanation of Angular dynamic components

Table of contents Usage scenarios How to achieve ...

Detailed explanation of rpm installation in mysql

View installation and uninstallation # View rpm -...

How to install the graphical interface in Linux

1. Linux installation (root user operation) 1. In...

Three ways to configure Nginx virtual hosts (based on domain names)

Nginx supports three ways to configure virtual ho...

Brief analysis of the MySQL character set causing database recovery errors

Importing data with incorrect MySQL character set...