Vue|vue3+ts+axios请求封装使用

Vue|vue3+ts+axios请求封装使用
文章图片

请求封装
实际使用中可以根据项目修改,比如RESTful api中可以自行添加put和delete请求,ResType也可以根据后端的通用返回值动态的去修改

//http.ts import axios from "axios" import NProgress from "nprogress" import type { App } from "vue" // const CancelToken = axios.CancelToken // const source = CancelToken.source()// 设置请求头和请求路径 axios.defaults.baseURL = "/api" axios.defaults.timeout = 10000 axios.defaults.headers.post["Content-Type"] = "application/json; charset=UTF-8" axios.interceptors.request.use( (config) => {const token = window.sessionStorage.getItem("token") if (token) {config.headers.token = token } return config }, (error) => {return error } ) // 响应拦截 axios.interceptors.response.use((res) => {if (res.data.code === 111) {sessionStorage.setItem("token", "") // token过期操作 } return res })interface ResType {code: number data?: T msg: string err?: string } interface Http {get(url: string, params?: unknown): Promise> post(url: string, params?: unknown): Promise> upload(url: string, params: unknown): Promise> download(url: string): void }const http: Http = {get(url, params) {return new Promise((resolve, reject) => {NProgress.start() axios .get(url, { params }) .then((res) => {NProgress.done() resolve(res.data) }) .catch((err) => {NProgress.done() reject(err.data) }) }) }, post(url, params) {return new Promise((resolve, reject) => {NProgress.start() axios .post(url, JSON.stringify(params)) .then((res) => {NProgress.done() resolve(res.data) }) .catch((err) => {NProgress.done() reject(err.data) }) }) }, upload(url, file) {return new Promise((resolve, reject) => {NProgress.start() axios .post(url, file, {headers: { "Content-Type": "multipart/form-data" }, }) .then((res) => {NProgress.done() resolve(res.data) }) .catch((err) => {NProgress.done() reject(err.data) }) }) }, download(url) {const iframe = document.createElement("iframe") iframe.style.display = "none" iframe.src = https://www.it610.com/article/url iframe.onload = function () {document.body.removeChild(iframe) } document.body.appendChild(iframe) } } export default http

调用请求
【Vue|vue3+ts+axios请求封装使用】请求的时候需要在泛型中传入返回值data的类型,下面是一个示例请求调用
//login.ts import http from "@/utils/http" const res = await http.post<{ user: UserState; token: string }>( "/user/login", formData ) if (res.code === 1) {store.commit("user/setUser", res.data?.user) sessionStorage.setItem("token", res.data?.token as string) } else {ElMessage.error(res.msg) }

    推荐阅读