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

Detailed installation process of mysql5.7.21 under win10

This article shares the installation of MySQL 5.7...

Comparison of the usage of EXISTS and IN in MySQL

1. Usage: (1) EXISTS usage select a.batchName,a.p...

Summary of practical skills commonly used in Vue projects

Table of contents Preface 1. Use $attrs and $list...

Teach you how to build Tencent Cloud Server (graphic tutorial)

This article was originally written by blogger We...

How to modify mysql permissions to allow hosts to access

Enable remote access rights for mysql By default,...

JavaScript to achieve the effect of tab bar switching

Tab bar: Click different tabs to display differen...

How to notify users of crontab execution results by email

symptom I set a crontab task on a centos7 host, b...

Sample code for deploying ELK using Docker-compose

environment Host IP 192.168.0.9 Docker version 19...

Detailed explanation of the pitfalls of mixing npm and cnpm

Table of contents cause reason Introduction to NP...

jQuery plugin to implement search history

A jQuery plugin every day - to make search histor...

HTTP and HTTP Collaboration Web Server Access Flow Diagram

A web server can build multiple web sites with in...

How to build your own Angular component library with DevUI

Table of contents Preface Creating a component li...

Summary of CSS3 practical methods (recommended)

1. Rounded border: CSS CodeCopy content to clipbo...

CentOS7 configuration Alibaba Cloud yum source method code

Open the centos yum folder Enter the command cd /...