No, no, it turns out that people are really in 2021, and they have never even heard of TypeScript, right? Although using TypeScript in a project will increase some development costs in the short term, TypeScript can reduce its maintenance costs for projects that require long-term maintenance. Using TypeScript increases the readability and maintainability of the code, and has a relatively active community. When it is a trend of being a big front-end, let's start to get up~
Encapsulation of basic axios library using TypeScript
The code is as follows:
// import axios, { AxiosRequestConfig, AxiosResponse } from 'axios' import { ElMessage } from "element-plus" const showStatus = (status: number) => { let message = '' switch (status) { case 400: message = 'Request error(400)' break case 401: message = 'Unauthorized,Please log in again(401)' break case 403: message = 'access denied(403)' break case 404: message = 'Request error(404)' break case 408: message = 'Request timeout(408)' break case 500: message = 'Server Error(500)' break case 501: message = 'Service not implemented(501)' break case 502: message = 'Network error(502)' break case 503: message = 'Service not available(503)' break case 504: message = 'Network timeout(504)' break case 505: message = 'HTTPVersion not supported(505)' break default: message = `There was an error in connection(${status})!` } return `${message},Please check the network or contact the administrator!` } const service = ({ // Joint commissioning // baseURL: .NODE_ENV === 'production' ? `/` : '/api', baseURL: "/api", headers: { get: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' }, post: { 'Content-Type': 'application/json;charset=utf-8' } }, // Whether to cross-site access control requests withCredentials: true, timeout: 30000, transformRequest: [(data) => { data = (data) return data }], validateStatus() { // Using async-await, it is more cumbersome to handle reject, so all return resolve and handle exceptions in business code return true }, transformResponse: [(data) => { if (typeof data === 'string' && ('{')) { data = (data) } return data }] }) // Request an interceptor((config: AxiosRequestConfig) => { //Get the token and add it to the request header let token = ('token') if(token){ = `${token}`; } return config }, (error) => { // Error thrown to business code = {} = 'The server is abnormal, please contact the administrator! ' return (error) }) // Response Interceptor((response: AxiosResponse) => { const status = let msg = '' if (status < 200 || status >= 300) { // Handle http errors and throw them into business code msg = showStatus(status) if (typeof === 'string') { = { msg } } else { = msg } } return response }, (error) => { if ((error)) { ('repeated request: ' + ) } else { // handle error code // Error thrown to business code = {} = 'Request timeout or server exception, please check the network or contact the administrator! ' () } return (error) }) export default service
Cancel multiple repeated request versions
Add the following code to the above code:
// import axios, { AxiosRequestConfig, AxiosResponse } from 'axios' import qs from "qs" import { ElMessage } from "element-plus" // Declare a Map to store the ID and cancel function for each requestconst pending = new Map() /** * Add a request * @param {Object} config */ const addPending = (config: AxiosRequestConfig) => { const url = [ , , (), () ].join('&') = || new (cancel => { if (!(url)) { // If the current request does not exist in pending, add it (url, cancel) } }) } /** * Removal request * @param {Object} config */ const removePending = (config: AxiosRequestConfig) => { const url = [ , , (), () ].join('&') if ((url)) { // If the current request identifier exists in pending, the current request needs to be cancelled and removed const cancel = (url) cancel(url) (url) } } /** * Clear the request in pending (called when the route jumps) */ export const clearPending = () => { for (const [url, cancel] of pending) { cancel(url) } () } // Request an interceptor((config: AxiosRequestConfig) => { removePending(config) // Before the request starts, check and cancel the previous request addPending(config) // Add the current request to pending let token = ('token') if(token){ = `${token}`; } return config }, (error) => { // Error thrown to business code = {} = 'The server is abnormal, please contact the administrator! ' return (error) }) // Response Interceptor((response: AxiosResponse) => { removePending(response) // After the request is completed, remove this request const status = let msg = '' if (status < 200 || status >= 300) { // Handle http errors and throw them into business code msg = showStatus(status) if (typeof === 'string') { = { msg } } else { = msg } } return response }, (error) => { if ((error)) { ('repeated request: ' + ) } else { // handle error code // Error thrown to business code = {} = 'Request timeout or server exception, please check the network or contact the administrator! ' () } return (error) }) export default service
Revoke all requests when routing jumps
Add to the routing file
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router' import Login from '@/views/Login/' //Introduce the clearPending function exposed in axiosimport { clearPending } from "@/api/axios" .... .... .... const router = createRouter({ history: createWebHistory(.BASE_URL), routes }) ((to, from, next) => { //Clear all requests before jumping the route clearPending() // ... next() }) export default router
Using encapsulated axios request library
Encapsulated response format
// Interface response through formatexport interface HttpResponse { status: number statusText: string data: { code: number desc: string [key: string]: any } }
Encapsulation interface method
Take a chestnut and encapsulate the User interface, the code is as follows ~
import Axios from './axios' import { HttpResponse } from '@/@types' /** * @interface loginParams -Login parameters * @property {string} username -username * @property {string} password -user password */ interface LoginParams { username: string password: string } //Encapsulation of User type interface methodexport class UserService { /** * @description Query User's information * @param {number} teamId - the team ID to be queryed * @return {HttpResponse} result */ static async login(params: LoginParams): Promise<HttpResponse> { return Axios('/api/user', { method: 'get', responseType: 'json', params: { ...params }, }) } static async resgister(params: LoginParams): Promise<HttpResponse> { return Axios('/api/user/resgister', { method: 'get', responseType: 'json', params: { ...params }, }) } }
Used in the project
The code is as follows:
<template> <input type="text" v-model="Account" placeholder="Please enter your account" name="username" > <input type="text" v-model="Password" placeholder="Please enter your password" name="username" > <button @="handleRegister()">Log in</button> </template> <script lang="ts"> import { defineComponent, reactive, toRefs } from 'vue' //Introduce interfaceimport { UserService } from '@/api/user' export default defineComponent({ setup() { const state = reactive({ Account: 'admin', //Account Password: 'hhhh', //password }) const handleLogin = async () => { const loginParams = { username: , password: , } const res = await (loginParams) (res) } const handleRegister = async () => { const loginParams = { username: , password: , } const res = await (loginParams) (res) } return { ...toRefs(state), handleLogin, handleRegister } }, }) </script>
This is the article about the implementation of Vue3+TypeScript encapsulating axios and making request calls. For more related content related to Vue3+TypeScript encapsulating axios, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!