Vue3+TypeScript封裝axios并進行請求調(diào)用的實現(xiàn)
不是吧,不是吧,原來真的有人都2021年了,連TypeScript都沒聽說過吧?在項目中使用TypeScript雖然短期內(nèi)會增加一些開發(fā)成本,但是對于其需要長期維護的項目,TypeScript能夠減少其維護成本,使用TypeScript增加了代碼的可讀性和可維護性,且擁有較為活躍的社區(qū),當居為大前端的趨勢所在,那就開始淦起來吧~
使用TypeScript封裝基礎axios庫
代碼如下:
// 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 = '服務未實現(xiàn)(501)'
break
case 502:
message = '網(wǎng)絡錯誤(502)'
break
case 503:
message = '服務不可用(503)'
break
case 504:
message = '網(wǎng)絡超時(504)'
break
case 505:
message = 'HTTP版本不受支持(505)'
break
default:
message = `連接出錯(${status})!`
}
return `${message},請檢查網(wǎng)絡或聯(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'
}
},
// 是否跨站點訪問控制請求
withCredentials: true,
timeout: 30000,
transformRequest: [(data) => {
data = JSON.stringify(data)
return data
}],
validateStatus() {
// 使用async-await,處理reject情況較為繁瑣,所以全部返回resolve,在業(yè)務代碼中處理異常
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) => {
// 錯誤拋到業(yè)務代碼
error.data = {}
error.data.msg = '服務器異常,請聯(lián)系管理員!'
return Promise.resolve(error)
})
// 響應攔截器
service.interceptors.response.use((response: AxiosResponse) => {
const status = response.status
let msg = ''
if (status < 200 || status >= 300) {
// 處理http錯誤,拋到業(yè)務代碼
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
// 錯誤拋到業(yè)務代碼
error.data = {}
error.data.msg = '請求超時或服務器異常,請檢查網(wǎng)絡或聯(lián)系管理員!'
ElMessage.error(error.data.msg)
}
return Promise.reject(error)
})
export default service
取消多次重復的請求版本
在上述代碼加入如下代碼:
// http.ts
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import qs from "qs"
import { ElMessage } from "element-plus"
// 聲明一個 Map 用于存儲每個請求的標識 和 取消函數(shù)
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 中的請求(在路由跳轉(zhuǎn)時調(diào)用)
*/
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) => {
// 錯誤拋到業(yè)務代碼
error.data = {}
error.data.msg = '服務器異常,請聯(lián)系管理員!'
return Promise.resolve(error)
})
// 響應攔截器
service.interceptors.response.use((response: AxiosResponse) => {
removePending(response) // 在請求結束后,移除本次請求
const status = response.status
let msg = ''
if (status < 200 || status >= 300) {
// 處理http錯誤,拋到業(yè)務代碼
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
// 錯誤拋到業(yè)務代碼
error.data = {}
error.data.msg = '請求超時或服務器異常,請檢查網(wǎng)絡或聯(lián)系管理員!'
ElMessage.error(error.data.msg)
}
return Promise.reject(error)
})
export default service
在路由跳轉(zhuǎn)時撤銷所有請求
在路由文件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)路由之前,先清除所有的請求
clearPending()
// ...
next()
})
export default router
使用封裝的axios請求庫
封裝響應格式
// 接口響應通過格式
export interface HttpResponse {
status: number
statusText: string
data: {
code: number
desc: string
[key: string]: any
}
}
封裝接口方法
舉個栗子,進行封裝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 - 所要查詢的團隊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
},
})
}
}
項目中進行使用
代碼如下:
<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并進行請求調(diào)用的實現(xiàn)的文章就介紹到這了,更多相關Vue3+TypeScript封裝axios內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
VUE搭建分布式醫(yī)療掛號系統(tǒng)后臺管理頁面示例步驟
這篇文章主要為大家介紹了分布式醫(yī)療掛號系統(tǒng)之搭建后臺管理系統(tǒng)頁面,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04
vue路由警告:Duplicate named routes definition問題
這篇文章主要介紹了vue路由警告:Duplicate named routes definition問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09

