Detailed explanation of interface request management based on Typescript and Axios

Detailed explanation of interface request management based on Typescript and Axios

This article mainly introduces interface request encapsulation based on TS and AXIOS

Ideas

Request interception

  • Add some parameters to the request header, such as token, uid, etc.
  • Determine the user's login status. If not logged in, jump directly to login
  • Process request data and convert the data format of the request to send, json→urlencoded (optional)

Response Interception

  • Determine the business status code of the backend response and perform different processing
    • For example, if the user's login status expires, jump directly to login
    • Unified error reporting

First write the routine code:

import axios, {
    AxiosInstance,
    AxiosResponse,
    AxiosRequestConfig,
    AxiosError
} from 'axios'
export default abstract class HttpClient {
    protected readonly instance: AxiosInstance

    public constructor(baseURL = '/api', timeout = 1000 * 120) {
        this.instance = axios.create({
            baseURL,
            timeout
        })
        // 1. Request interceptor this._initializeRequestInterceptor()
        // 2. Response interceptor this._initializeResponseInterceptor()
    }
    private _initializeRequestInterceptor = () => {
        this.instance.interceptors.request.use(
            this._handleRequest,
            this._handleError
        )
    }
    private _handleRequest = (config: AxiosRequestConfig) => {}
   
    private _initializeResponseInterceptor = () => {
        this.instance.interceptors.response.use(
            this._handleResponse,
            this._handleError
        )
    }
    private _handleResponse = (response: AxiosResponse) => {}
    protected _handleError = (error: AxiosError) => Promise.reject(error)
}

To briefly explain the above code, we created an HttpClient class for the request interface, defined the baseURL and timeout in the constructor, and defined the request interception method and response interception method.

At this point, the process of initiating an interface is as follows:

  1. Before sending the request, call request interception
  2. Send interface, network request appears
  3. Interface response, call response interception
  4. Respond to the front-end program and execute the corresponding logic

Request interception

Let's start with the detailed logic. When requesting interception, you can do the following:

  1. Add some parameters to the request header, such as token, uid, etc.
  2. Determine the user's login status. If not logged in, jump directly to login
  3. Process request data and convert the data format of the request to send, json→urlencoded (optional)
     private _handleRequest = (config: AxiosRequestConfig) => {
        //1. Add a custom request header config.headers['Authorization'] = 'my token'
        config.headers['mobile'] = 'my mobile'
        //2. Determine whether to log in (determine whether there is a token)
        
        //3. Convert data format config.data = qs.stringify(config.data)
        return config
    }

Response Interception

After getting the response, the process is as follows:

  • Determine the business status code of the backend response and perform different processing
    • If the user's login status expires, jump directly to login
    • Unified error reporting
  • Save token
 // Response interceptor private _handleResponse = (response: AxiosResponse) => {
        const { data, headers } = response

        //1.--Process the response token and save the token
        const token = headers['authorization']
        if (token) {
            this._saveToken(token)
        }
       
        //2. --Process the response code, try-catch here, if some backend interfaces do not return code, return directly to try {
            const code = data.code,
            message = data.desc || data.msg
            const isSucceed = this._handleResCode(code, message, url)
            if (isSucceed) {
                return Promise.resolve(data)
            } else {
                return Promise.reject(message)
            }
        } catch (error) {
            return Promise.resolve(data)
        }
       
    }
    //Save token
    private _saveToken(token: string) {
        const USER = getModule(UserModule)
        USER.setToken(token)
    }
    private _handleResCode(code: number, message: string, url: string) {
        if (code === 0) {
            // Request successful return true
        } else if (code===4000) {
            // Token expires, jump back to the login interface Vue.prototype.$message.error('Identity information expired, please log in again')
            router.push({ name: 'login' })
            return false
        } else {
            // In other cases, all prompts are message information Vue.prototype.$message.error(message)
            return false
        }
    }

Define the request using httpClient.ts

It is recommended that request-related files be defined in the @/api directory, as follows

httpClient.ts
user.ts
uti.ts

Define the request in the corresponding file, note

  1. All request classes need to inherit the HttpClient class. HttpClient does some unified interception and unified processing of requests and responses.
  2. The data of the request response needs to provide a type, which is defined in the @/types/xxx file. One module corresponds to one file. Only when the type is provided will there be code hints
import HttpClient from './HttpClient'
import { AlarmItemType } from '../types/test'
import { BaseResType } from '../types/index'

class UtilApi extends HttpClient {
   //For example, the response returned by the background res={code:xxx,data:xxx,token:xxx,desc:xxx}
    //First, you need to define the type of res.data, which is the first parameter of get, AlarmItemType
    //Then you need to define the type of the entire response, which is BaseResType<AlarmItemType>
    public getAlarmById = (id: string) =>
        this.instance.get<AlarmItemType, BaseResType<AlarmItemType>>(
            `/realtime/alarms/queryByAlarmId/${id}`
        )
}

export const UTIL_API = new UtilApi()

Requesting an interface in a component

Type the keyword of the request module in the component to which you need to send a request, such as USER_API. If the TypeScript Importer plug-in is installed, there will be a corresponding module import prompt. At this time, press Enter to import the corresponding module.

<template>
    <section>Request data:{{ alarmData }}</section>
</template>

<script lang="ts">
import { UTIL_API } from '@/api/utilApi'
import { Vue, Component } from 'vue-property-decorator'
@Component({
    components: {}
})
export default class TestRequest extends Vue {
    alarmData = {}
    async getAlarmData() {
        const res = await UTIL_API.getAlarmById('alarmIdc7e9bd47')
        if (res.code == 0) {
            this.$message.success('Request successful')
            this.alarmData = res.data
        }
    }
    mounted() {
        this.getAlarmData()
    }
}
</script>
<style lang="scss" scoped></style>

Summarize

This is the end of this article on interface request management based on Typescript and Axios. For more related Typescript and Axios interface request content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • TypeScript interface definition case tutorial
  • TypeScript generic usage and generic interface combination
  • Introduction to TypeScript interfaces
  • TypeScript Introduction - Interface
  • Detailed explanation of interfaces in TypeScript
  • TypeScript Core Foundation Interface

<<:  VMware15.5 installation Ubuntu20.04 graphic tutorial

>>:  Ubuntu 20.04 connects to wifi (2 methods)

Recommend

How to implement scheduled backup of MySQL database

1. Create a shell script vim backupdb.sh Create t...

WeChat applet implements a simple handwritten signature component

Table of contents background: need: Effect 1. Ide...

How to reset the root password in mysql8.0.12

After installing the database, if you accidentall...

In-depth understanding of the use of the infer keyword in typescript

Table of contents infer Case: Deepen your underst...

Solution to span width not being determined in Firefox or IE

Copy code The code is as follows: <html xmlns=...

Implementation of local migration of docker images

I've been learning Docker recently, and I oft...

Vue makes div height draggable

This article shares the specific code of Vue to r...

Nginx memory pool source code analysis

Table of contents Memory Pool Overview 1. nginx d...

Summary of Vue3 combined with TypeScript project development practice

Table of contents Overview 1. Compositon API 1. W...

How to package the uniapp project as a desktop application

Installing Electron cnpm install electron -g Inst...

Share 16 burning flame effect English fonts treasure trove

We live in a visual world and are surrounded by m...