Vue3+TypeScript封裝axios并進(jìn)行請(qǐng)求調(diào)用的實(shí)現(xiàn)
不是吧,不是吧,原來(lái)真的有人都2021年了,連TypeScript都沒(méi)聽說(shuō)過(guò)吧?在項(xiàng)目中使用TypeScript雖然短期內(nèi)會(huì)增加一些開發(fā)成本,但是對(duì)于其需要長(zhǎng)期維護(hù)的項(xiàng)目,TypeScript能夠減少其維護(hù)成本,使用TypeScript增加了代碼的可讀性和可維護(hù)性,且擁有較為活躍的社區(qū),當(dāng)居為大前端的趨勢(shì)所在,那就開始淦起來(lái)吧~
使用TypeScript封裝基礎(chǔ)axios庫(kù)
代碼如下:
// http.ts
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from "element-plus"
const showStatus = (status: number) => {
let message = ''
switch (status) {
case 400:
message = '請(qǐng)求錯(cuò)誤(400)'
break
case 401:
message = '未授權(quán),請(qǐng)重新登錄(401)'
break
case 403:
message = '拒絕訪問(wèn)(403)'
break
case 404:
message = '請(qǐng)求出錯(cuò)(404)'
break
case 408:
message = '請(qǐng)求超時(shí)(408)'
break
case 500:
message = '服務(wù)器錯(cuò)誤(500)'
break
case 501:
message = '服務(wù)未實(shí)現(xiàn)(501)'
break
case 502:
message = '網(wǎng)絡(luò)錯(cuò)誤(502)'
break
case 503:
message = '服務(wù)不可用(503)'
break
case 504:
message = '網(wǎng)絡(luò)超時(shí)(504)'
break
case 505:
message = 'HTTP版本不受支持(505)'
break
default:
message = `連接出錯(cuò)(${status})!`
}
return `${message},請(qǐng)檢查網(wǎng)絡(luò)或聯(lián)系管理員!`
}
const service = axios.create({
// 聯(lián)調(diào)
// 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'
}
},
// 是否跨站點(diǎn)訪問(wèn)控制請(qǐng)求
withCredentials: true,
timeout: 30000,
transformRequest: [(data) => {
data = JSON.stringify(data)
return data
}],
validateStatus() {
// 使用async-await,處理reject情況較為繁瑣,所以全部返回resolve,在業(yè)務(wù)代碼中處理異常
return true
},
transformResponse: [(data) => {
if (typeof data === 'string' && data.startsWith('{')) {
data = JSON.parse(data)
}
return data
}]
})
// 請(qǐng)求攔截器
service.interceptors.request.use((config: AxiosRequestConfig) => {
//獲取token,并將其添加至請(qǐng)求頭中
let token = localStorage.getItem('token')
if(token){
config.headers.Authorization = `${token}`;
}
return config
}, (error) => {
// 錯(cuò)誤拋到業(yè)務(wù)代碼
error.data = {}
error.data.msg = '服務(wù)器異常,請(qǐng)聯(lián)系管理員!'
return Promise.resolve(error)
})
// 響應(yīng)攔截器
service.interceptors.response.use((response: AxiosResponse) => {
const status = response.status
let msg = ''
if (status < 200 || status >= 300) {
// 處理http錯(cuò)誤,拋到業(yè)務(wù)代碼
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
// 錯(cuò)誤拋到業(yè)務(wù)代碼
error.data = {}
error.data.msg = '請(qǐng)求超時(shí)或服務(wù)器異常,請(qǐng)檢查網(wǎng)絡(luò)或聯(lián)系管理員!'
ElMessage.error(error.data.msg)
}
return Promise.reject(error)
})
export default service
取消多次重復(fù)的請(qǐng)求版本
在上述代碼加入如下代碼:
// http.ts
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import qs from "qs"
import { ElMessage } from "element-plus"
// 聲明一個(gè) Map 用于存儲(chǔ)每個(gè)請(qǐng)求的標(biāo)識(shí) 和 取消函數(shù)
const pending = new Map()
/**
* 添加請(qǐng)求
* @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 中不存在當(dāng)前請(qǐng)求,則添加進(jìn)去
pending.set(url, cancel)
}
})
}
/**
* 移除請(qǐng)求
* @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 中存在當(dāng)前請(qǐng)求標(biāo)識(shí),需要取消當(dāng)前請(qǐng)求,并且移除
const cancel = pending.get(url)
cancel(url)
pending.delete(url)
}
}
/**
* 清空 pending 中的請(qǐng)求(在路由跳轉(zhuǎn)時(shí)調(diào)用)
*/
export const clearPending = () => {
for (const [url, cancel] of pending) {
cancel(url)
}
pending.clear()
}
// 請(qǐng)求攔截器
service.interceptors.request.use((config: AxiosRequestConfig) => {
removePending(config) // 在請(qǐng)求開始前,對(duì)之前的請(qǐng)求做檢查取消操作
addPending(config) // 將當(dāng)前請(qǐng)求添加到 pending 中
let token = localStorage.getItem('token')
if(token){
config.headers.Authorization = `${token}`;
}
return config
}, (error) => {
// 錯(cuò)誤拋到業(yè)務(wù)代碼
error.data = {}
error.data.msg = '服務(wù)器異常,請(qǐng)聯(lián)系管理員!'
return Promise.resolve(error)
})
// 響應(yīng)攔截器
service.interceptors.response.use((response: AxiosResponse) => {
removePending(response) // 在請(qǐng)求結(jié)束后,移除本次請(qǐng)求
const status = response.status
let msg = ''
if (status < 200 || status >= 300) {
// 處理http錯(cuò)誤,拋到業(yè)務(wù)代碼
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
// 錯(cuò)誤拋到業(yè)務(wù)代碼
error.data = {}
error.data.msg = '請(qǐng)求超時(shí)或服務(wù)器異常,請(qǐng)檢查網(wǎng)絡(luò)或聯(lián)系管理員!'
ElMessage.error(error.data.msg)
}
return Promise.reject(error)
})
export default service
在路由跳轉(zhuǎn)時(shí)撤銷所有請(qǐng)求
在路由文件index.ts中加入
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Login from '@/views/Login/Login.vue'
//引入在axios暴露出的clearPending函數(shù)
import { clearPending } from "@/api/axios"
....
....
....
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
router.beforeEach((to, from, next) => {
//在跳轉(zhuǎn)路由之前,先清除所有的請(qǐng)求
clearPending()
// ...
next()
})
export default router
使用封裝的axios請(qǐng)求庫(kù)
封裝響應(yīng)格式
// 接口響應(yīng)通過(guò)格式
export interface HttpResponse {
status: number
statusText: string
data: {
code: number
desc: string
[key: string]: any
}
}
封裝接口方法
舉個(gè)栗子,進(jìn)行封裝User接口,代碼如下~
import Axios from './axios'
import { HttpResponse } from '@/@types'
/**
* @interface loginParams -登錄參數(shù)
* @property {string} username -用戶名
* @property {string} password -用戶密碼
*/
interface LoginParams {
username: string
password: string
}
//封裝User類型的接口方法
export class UserService {
/**
* @description 查詢User的信息
* @param {number} teamId - 所要查詢的團(tuán)隊(duì)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
},
})
}
}
項(xiàng)目中進(jìn)行使用
代碼如下:
<template>
<input type="text" v-model="Account" placeholder="請(qǐng)輸入賬號(hào)" name="username" >
<input type="text" v-model="Password" placeholder="請(qǐng)輸入密碼" 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>
到此這篇關(guān)于Vue3+TypeScript封裝axios并進(jìn)行請(qǐng)求調(diào)用的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Vue3+TypeScript封裝axios內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于element-ui封裝可搜索的懶加載tree組件的實(shí)現(xiàn)
這篇文章主要介紹了基于element-ui封裝可搜索的懶加載tree組件的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
vue中elementUI表單循環(huán)驗(yàn)證方式
這篇文章主要介紹了vue中elementUI表單循環(huán)驗(yàn)證方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10
Vue+thinkphp5.1+axios實(shí)現(xiàn)文件上傳
這篇文章主要為大家詳細(xì)介紹了Vue+thinkphp5.1+axios實(shí)現(xiàn)文件上傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-05-05
使用vue實(shí)現(xiàn)一個(gè)電子簽名組件的示例代碼
這篇文章主要介紹了使用vue實(shí)現(xiàn)一個(gè)電子簽名組件的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01
Vue引入vuetify框架你需要知道的幾點(diǎn)知識(shí)
這篇文章主要介紹了Vue引入vuetify框架你需要知道的幾點(diǎn)知識(shí),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
Vue3中關(guān)于ref和reactive的區(qū)別分析
這篇文章主要介紹了vue3關(guān)于ref和reactive的區(qū)別分析,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2023-06-06
如何用vue-cli3腳手架搭建一個(gè)基于ts的基礎(chǔ)腳手架的方法
這篇文章主要介紹了如何用vue-cli3腳手架搭建一個(gè)基于ts的基礎(chǔ)腳手架的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12

