本文旨在介紹如何在 vite+vue3+ts的項目中使用 aixos 來做數(shù)據(jù)請求。以及二次封裝完整使用套路。
1. 安裝 axios
安裝指令
yarn add axios
2. 封裝
2.1 封裝實現(xiàn)功能
- 優(yōu)化請求代碼量,統(tǒng)一處理請求、請求頭、請求簽名、加密、請求攔截、響應攔截等;
- 根據(jù)不同業(yè)務邏輯拆分代碼,盡可能的實現(xiàn)業(yè)務解耦;
2.2 封裝步驟
-
在
src目錄下創(chuàng)建api目錄,并初始化以下文件:目錄文件 說明 src/api/index.tsaxios入口文件,所有接口相關功能都可以從此文件引入后再集中導出 src/api/http.tsaxios請求,請求簽名,請求加密,請求攔截,響應攔截等統(tǒng)一處理文件 src/api/common/index.ts通用接口模塊,比如獲取按鈕權限,字典值等接口 src/api/其他/index.ts具體業(yè)務模塊,比如登錄校驗可以定義為 src/api/auth/index.ts -
src/api/index.ts/** * ! axios入口文件,所有接口相關功能都可以從此文件引入后再集中導出 * 1. 集中管理管理當前環(huán)境使用的后端服務地址 * 2. 統(tǒng)一把各個模塊的接口導入到該文件,統(tǒng)一導出 * 3. 調用時只需要 api.common.reqGetDogs() 來調用接口,common為模塊名稱,reqGetDogs為接口名稱 */ // 后臺地址--后續(xù)配置環(huán)境變量時優(yōu)化 export const BASE: string = 'http://xxx.xxx.xx:8087' // 通用接口 import * as common from './common' // 其他模塊接口 export default { common } -
src/api/http.ts/* eslint-disable @typescript-eslint/no-explicit-any */ import axios, { type InternalAxiosRequestConfig } from 'axios' import { ElMessage } from 'element-plus' interface AnyObject { [key: string]: any } // 請求攔截器 axios.interceptors.request.use((req: InternalAxiosRequestConfig) => { /** * ! 根據(jù)業(yè)務需求和后端配置約定如何定義請求攔截器 * 1. 添加請求頭 * 2. 添加token * 3. 配置參數(shù)格式 * 4. 配置簽名 * 5. 配置其他參數(shù) */ req.headers['Content-Type'] = 'application/json' /* if (localStorage.getItem('token') && !req.headers['Authorization']) { req.headers['Authorization'] = localStorage.getItem('token') } */ return req }) // 響應攔截器 axios.interceptors.response.use( (response) => { /** * ! 根據(jù)業(yè)務需求和后端配置約定如何定義響應攔截器 * 1. 響應數(shù)據(jù)處理,統(tǒng)一格式化響應數(shù)據(jù) * 2. 響應錯誤處理 */ return response }, (error) => { ElMessage.error('數(shù)據(jù)獲取失敗!') return Promise.reject(error) }, ) const http = (url: string, data: AnyObject = {}, type: string = 'POST') => { return new Promise<any>((resolve, reject) => { let promise if (type === 'GET') { promise = axios.get(url, { params: data }) } else if (type === 'POST') { promise = axios.post(url, data) } promise ?.then((response: AnyObject) => { resolve(response.data) }) .catch((error: AnyObject) => { ElMessage.error('數(shù)據(jù)獲取失敗!') console.log(error) reject(error) }) }) } export default http
-
src/api/common/index.tsimport http from '@api/http.ts' import { BASE } from '@api/index.ts' interface IParrms { username: string password: string } // http 接三個參數(shù),url必填, params默認空對象可以不寫, get或者post默認post可以不寫, // 登陸login export const ReqLogin = (params: IParrms) => http(`${BASE}/login`, params) // 測試獲取狗狗照片 到App.vue中執(zhí)行獲取動作 export const ReqGetDogs = () => http(`https://dog.ceo/api/breeds/image/random`, {}, 'GET')
3. 調用demo
-
引入接口
// 方式1 import api from '@api/index.ts' // 方式2 import ReqGetDogs from '@api/common/index.ts'
-
調用接口demo
const getDogPic = async () => { // 調用方式1 const res = await api.common.ReqGetDogs() // 調用方式2 const res = await ReqGetDogs() console.log(res) } onMounted(() => { getDogPic() })