不是吧,不是吧,原來真的有人都2021年了,連TypeScript都沒聽說過吧?在項目中使用TypeScript雖然短期內會增加一些開發成本,但是對于其需要長期維護的項目,TypeScript能夠減少其維護成本,使用TypeScript增加了代碼的可讀性和可維護性,且擁有較為活躍的社區,當居為大前端的趨勢所在,那就開始淦起來吧~
使用TypeScript封裝基礎axios庫
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
|
// http.ts import axios, { AxiosRequestConfig, AxiosResponse } from 'axios' import { ElMessage } from "element-plus" const showStatus = (status: number) => { let message = '' switch (status) { case 400: message = '請求錯誤(400)' break case 401: message = '未授權,請重新登錄(401)' break case 403: message = '拒絕訪問(403)' break case 404: message = '請求出錯(404)' break case 408: message = '請求超時(408)' break case 500: message = '服務器錯誤(500)' break case 501: message = '服務未實現(501)' break case 502: message = '網絡錯誤(502)' break case 503: message = '服務不可用(503)' break case 504: message = '網絡超時(504)' break case 505: message = 'HTTP版本不受支持(505)' break default : message = `連接出錯(${status})!` } return `${message},請檢查網絡或聯系管理員!` } const service = axios.create({ // 聯調 // baseURL: process.env.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' } }, // 是否跨站點訪問控制請求 withCredentials: true , timeout: 30000, transformRequest: [(data) => { data = JSON.stringify(data) return data }], validateStatus() { // 使用async-await,處理reject情況較為繁瑣,所以全部返回resolve,在業務代碼中處理異常 return true }, transformResponse: [(data) => { if ( typeof data === 'string' && data.startsWith( '{' )) { data = JSON.parse(data) } return data }] }) // 請求攔截器 service.interceptors.request.use((config: AxiosRequestConfig) => { //獲取token,并將其添加至請求頭中 let token = localStorage.getItem( 'token' ) if (token){ config.headers.Authorization = `${token}`; } return config }, (error) => { // 錯誤拋到業務代碼 error.data = {} error.data.msg = '服務器異常,請聯系管理員!' return Promise.resolve(error) }) // 響應攔截器 service.interceptors.response.use((response: AxiosResponse) => { const status = response.status let msg = '' if (status < 200 || status >= 300) { // 處理http錯誤,拋到業務代碼 msg = showStatus(status) if ( typeof response.data === 'string' ) { response.data = { msg } } else { response.data.msg = msg } } return response }, (error) => { if (axios.isCancel(error)) { console.log( 'repeated request: ' + error.message) } else { // handle error code // 錯誤拋到業務代碼 error.data = {} error.data.msg = '請求超時或服務器異常,請檢查網絡或聯系管理員!' ElMessage.error(error.data.msg) } return Promise.reject(error) }) export default service |
取消多次重復的請求版本
在上述代碼加入如下代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
// http.ts import axios, { AxiosRequestConfig, AxiosResponse } from 'axios' import qs from "qs" import { ElMessage } from "element-plus" // 聲明一個 Map 用于存儲每個請求的標識 和 取消函數 const pending = new Map() /** * 添加請求 * @param {Object} config */ const addPending = (config: AxiosRequestConfig) => { const url = [ config.method, config.url, qs.stringify(config.params), qs.stringify(config.data) ].join( '&' ) config.cancelToken = config.cancelToken || new axios.CancelToken(cancel => { if (!pending.has(url)) { // 如果 pending 中不存在當前請求,則添加進去 pending.set(url, cancel) } }) } /** * 移除請求 * @param {Object} config */ const removePending = (config: AxiosRequestConfig) => { const url = [ config.method, config.url, qs.stringify(config.params), qs.stringify(config.data) ].join( '&' ) if (pending.has(url)) { // 如果在 pending 中存在當前請求標識,需要取消當前請求,并且移除 const cancel = pending.get(url) cancel(url) pending. delete (url) } } /** * 清空 pending 中的請求(在路由跳轉時調用) */ export const clearPending = () => { for (const [url, cancel] of pending) { cancel(url) } pending.clear() } // 請求攔截器 service.interceptors.request.use((config: AxiosRequestConfig) => { removePending(config) // 在請求開始前,對之前的請求做檢查取消操作 addPending(config) // 將當前請求添加到 pending 中 let token = localStorage.getItem( 'token' ) if (token){ config.headers.Authorization = `${token}`; } return config }, (error) => { // 錯誤拋到業務代碼 error.data = {} error.data.msg = '服務器異常,請聯系管理員!' return Promise.resolve(error) }) // 響應攔截器 service.interceptors.response.use((response: AxiosResponse) => { removePending(response) // 在請求結束后,移除本次請求 const status = response.status let msg = '' if (status < 200 || status >= 300) { // 處理http錯誤,拋到業務代碼 msg = showStatus(status) if ( typeof response.data === 'string' ) { response.data = { msg } } else { response.data.msg = msg } } return response }, (error) => { if (axios.isCancel(error)) { console.log( 'repeated request: ' + error.message) } else { // handle error code // 錯誤拋到業務代碼 error.data = {} error.data.msg = '請求超時或服務器異常,請檢查網絡或聯系管理員!' ElMessage.error(error.data.msg) } return Promise.reject(error) }) export default service |
在路由跳轉時撤銷所有請求
在路由文件index.ts中加入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router' import Login from '@/views/Login/Login.vue' //引入在axios暴露出的clearPending函數 import { clearPending } from "@/api/axios" .... .... .... const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes }) router.beforeEach((to, from, next) => { //在跳轉路由之前,先清除所有的請求 clearPending() // ... next() }) export default router |
使用封裝的axios請求庫
封裝響應格式
1
2
3
4
5
6
7
8
9
10
|
// 接口響應通過格式 export interface HttpResponse { status: number statusText: string data: { code: number desc: string [key: string]: any } } |
封裝接口方法
舉個栗子,進行封裝User接口,代碼如下~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
import Axios from './axios' import { HttpResponse } from '@/@types' /** * @interface loginParams -登錄參數 * @property {string} username -用戶名 * @property {string} password -用戶密碼 */ interface LoginParams { username: string password: string } //封裝User類型的接口方法 export class UserService { /** * @description 查詢User的信息 * @param {number} teamId - 所要查詢的團隊ID * @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 }, }) } } |
項目中進行使用
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
<template> <input type= "text" v-model= "Account" placeholder= "請輸入賬號" name= "username" > <input type= "text" v-model= "Password" placeholder= "請輸入密碼" name= "username" > <button @click.prevent= "handleRegister()" >登錄</button> </template> <script lang= "ts" > import { defineComponent, reactive, toRefs } from 'vue' //引入接口 import { UserService } from '@/api/user' export default defineComponent({ setup() { const state = reactive({ Account: 'admin' , //賬戶 Password: 'hhhh' , //密碼 }) const handleLogin = async () => { const loginParams = { username: state.Account, password: state.Password, } const res = await UserService.login(loginParams) console.log(res) } const handleRegister = async () => { const loginParams = { username: state.Account, password: state.Password, } const res = await UserService.resgister(loginParams) console.log(res) } return { ...toRefs(state), handleLogin, handleRegister } }, }) </script> |
到此這篇關于Vue3+TypeScript封裝axios并進行請求調用的實現的文章就介紹到這了,更多相關Vue3+TypeScript封裝axios內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://segmentfault.com/a/1190000039806000