不是吧,不是吧,原來真的有人都2021年了,連TypeScript都沒據說過吧?在項目中使用TypeScript雖然短時間內會增長一些開發成本,可是對於其須要長期維護的項目,TypeScript可以減小其維護成本,使用TypeScript增長了代碼的可讀性和可維護性,且擁有較爲活躍的社區,當居爲大前端的趨勢所在,那就開始淦起來吧~前端
代碼以下:vue
// 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
在上述代碼加入以下代碼:react
// 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中加入ios
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
// 接口響應經過格式 export interface HttpResponse { status: number statusText: string data: { code: number desc: string [key: string]: any } }
舉個栗子,進行封裝User接口,代碼以下~vue-router
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 }, }) } }
代碼以下:typescript
<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>