From 67bee60ed3e29eac6ce31f9a39e769fd0ac13776 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8F=B2=E9=B8=BD?= <1020103647@qq.com> Date: Thu, 1 Feb 2024 19:51:58 +0800 Subject: [PATCH] feat: ts --- src/typings.d.ts | 9 +++++++++ src/utils/http.ts | 16 ++++------------ 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/typings.d.ts b/src/typings.d.ts index c1e9c5c..9878916 100644 --- a/src/typings.d.ts +++ b/src/typings.d.ts @@ -1,3 +1,11 @@ +// 全局要用的类型放到这里 + +export type IResData = { + 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 diff --git a/src/utils/http.ts b/src/utils/http.ts index 0495f0e..79ace68 100644 --- a/src/utils/http.ts +++ b/src/utils/http.ts @@ -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 } -type Data = { - 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 = (options: CustomRequestOptions) => { // 1. 返回 Promise 对象 - return new Promise>((resolve, reject) => { + return new Promise>((resolve, reject) => { uni.request({ ...options, dataType: 'json', @@ -68,7 +60,7 @@ export const http = (options: CustomRequestOptions) => { // 状态码 2xx,参考 axios 的设计 if (res.statusCode >= 200 && res.statusCode < 300) { // 2.1 提取核心数据 res.data - resolve(res.data as Data) + resolve(res.data as IResData) } else if (res.statusCode === 401) { // 401错误 -> 清理用户信息,跳转到登录页 // userStore.clearUserInfo() @@ -78,7 +70,7 @@ export const http = (options: CustomRequestOptions) => { // 其他错误 -> 根据后端错误信息轻提示 uni.showToast({ icon: 'none', - title: (res.data as Data).msg || '请求错误', + title: (res.data as IResData).msg || '请求错误', }) reject(res) }