This commit is contained in:
菲鸽 2024-02-01 19:51:58 +08:00
parent ff126f8f99
commit 67bee60ed3
2 changed files with 13 additions and 12 deletions

9
src/typings.d.ts vendored
View File

@ -1,3 +1,11 @@
// 全局要用的类型放到这里
export type IResData<T> = {
code: number
msg: string
result: T
}
export type UserInfo = {
nickname?: string
avatar?: string
@ -5,6 +13,7 @@ export type UserInfo = {
openid?: string
token?: string
}
export type UserItem = {
username: string
age: number

View File

@ -1,16 +1,10 @@
/* eslint-disable no-param-reassign */
import qs from 'qs'
import { useUserStore } from '@/store'
import { UserInfo } from '@/typings'
import { IResData, UserInfo } from '@/typings'
type CustomRequestOptions = UniApp.RequestOptions & { query?: Record<string, any> }
type Data<T> = {
code: number
msg: string
result: T
}
// 请求基地址
const baseURL = import.meta.env.VITE_SERVER_BASEURL
// console.log(import.meta.env)
@ -19,8 +13,6 @@ const baseURL = import.meta.env.VITE_SERVER_BASEURL
const httpInterceptor = {
// 拦截前触发
invoke(options: CustomRequestOptions) {
console.log(options)
// 接口请求支持通过 query 参数配置 queryString
if (options.query) {
const queryStr = qs.stringify(options.query)
@ -58,7 +50,7 @@ uni.addInterceptor('uploadFile', httpInterceptor)
export const http = <T>(options: CustomRequestOptions) => {
// 1. 返回 Promise 对象
return new Promise<Data<T>>((resolve, reject) => {
return new Promise<IResData<T>>((resolve, reject) => {
uni.request({
...options,
dataType: 'json',
@ -68,7 +60,7 @@ export const http = <T>(options: CustomRequestOptions) => {
// 状态码 2xx参考 axios 的设计
if (res.statusCode >= 200 && res.statusCode < 300) {
// 2.1 提取核心数据 res.data
resolve(res.data as Data<T>)
resolve(res.data as IResData<T>)
} else if (res.statusCode === 401) {
// 401错误 -> 清理用户信息,跳转到登录页
// userStore.clearUserInfo()
@ -78,7 +70,7 @@ export const http = <T>(options: CustomRequestOptions) => {
// 其他错误 -> 根据后端错误信息轻提示
uni.showToast({
icon: 'none',
title: (res.data as Data<T>).msg || '请求错误',
title: (res.data as IResData<T>).msg || '请求错误',
})
reject(res)
}