This article mainly introduces interface request encapsulation based on TS and AXIOS IdeasRequest interception
Response Interception
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:
Request interceptionLet's start with the detailed logic. When requesting interception, you can do the following:
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 InterceptionAfter getting the response, the process is as follows:
// 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.tsIt 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
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 componentType 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> SummarizeThis 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:
|
<<: VMware15.5 installation Ubuntu20.04 graphic tutorial
>>: Ubuntu 20.04 connects to wifi (2 methods)
//MySQL statement SELECT * FROM `MyTable` WHERE `...
This article records the installation and configu...
CJK is the abbreviation of CJK Unified Ideographs...
Table of contents 1. Download nodejs 2. Double-cl...
How to view linux files Command to view file cont...
After a lot of trouble, I finally figured out the...
What is MIME TYPE? 1. First, we need to understan...
1. z-index is invalid in IE6. In CSS, the z-index...
This article records the specific method of insta...
Use OSS to upload pictures or attachments in vue ...
Let’s take a look at a chestnut first EXPLAIN sel...
First, a common question is, what is the relation...
01. VMware Workstation Pro 15 Download Download: ...
Recently, I'm learning to use React with Thre...
need: Use vue to realize QR code scanning; Plugin...