diff --git a/src/pages/index/index.vue b/src/pages/index/index.vue index 436eb9a..693e734 100644 --- a/src/pages/index/index.vue +++ b/src/pages/index/index.vue @@ -30,14 +30,14 @@ }); }; - import { defHttp } from '@/utils/http/index'; + import { request } from '@/utils/http/index'; const form = reactive({ email: 'catch@admin.com', password: 'catchadmin', }); const loginType = ref(''); const submit = () => { - defHttp + request .post('/login', form) .then((res) => { loginType.value = '登录成功'; diff --git a/src/pages/login/index.vue b/src/pages/login/index.vue index 20720db..1ac89d5 100644 --- a/src/pages/login/index.vue +++ b/src/pages/login/index.vue @@ -18,7 +18,7 @@ diff --git a/src/services/api/user.ts b/src/services/api/user.ts new file mode 100644 index 0000000..06c6cb6 --- /dev/null +++ b/src/services/api/user.ts @@ -0,0 +1,7 @@ +import { request } from '@/utils/http'; + +const LOGIN = '/login'; + +export function login(params: LoginParams) { + return request.post>(LOGIN, params); +} diff --git a/src/services/model/baseModel.d.ts b/src/services/model/baseModel.d.ts new file mode 100644 index 0000000..06105c8 --- /dev/null +++ b/src/services/model/baseModel.d.ts @@ -0,0 +1,5 @@ +declare interface API { + code: number; + data?: T; + message: string; +} diff --git a/src/services/model/user.d.ts b/src/services/model/user.d.ts new file mode 100644 index 0000000..76f8681 --- /dev/null +++ b/src/services/model/user.d.ts @@ -0,0 +1,7 @@ +declare interface LoginParams { + email: string; + password: string; +} +declare interface LoginModel { + token: string; +} diff --git a/src/settings/encryptionSetting.ts b/src/settings/encryptionSetting.ts index 76efeb4..22dd24e 100644 --- a/src/settings/encryptionSetting.ts +++ b/src/settings/encryptionSetting.ts @@ -2,7 +2,8 @@ import { getPkgVersion, isDevMode } from '@/utils/env'; // System default cache time, in seconds export const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7; -const PREFIX = import.meta.env.VITE_APP_CACHE_PREFIX || 'UNI_APP_VUE3_TS'; +const PREFIX = + import.meta.env.VITE_APP_CACHE_PREFIX || import.meta.env.VITE_APP_TITLE || 'UNI_APP_VUE3_TS'; export const DEFAULT_PREFIX_KEY = `${PREFIX}${getPkgVersion()}`; // aes encryption key diff --git a/src/state/modules/user.ts b/src/state/modules/user.ts index 72f26f5..0f451c0 100644 --- a/src/state/modules/user.ts +++ b/src/state/modules/user.ts @@ -1,6 +1,7 @@ import { defineStore } from 'pinia'; import { getCache, setCache } from '@/utils/catch'; import { TOKEN_KEY } from '@/enums/cacheEnum'; +import { login } from '@/services/api/user'; interface UserState { token?: string; @@ -19,5 +20,17 @@ export const useUserStore = defineStore({ setCache(TOKEN_KEY, token); this.token = token; }, + /** + * @description 登录 + */ + async login(params: LoginParams): Promise { + try { + const { data } = await login(params); + this.setToken(data.token); + return Promise.resolve(data); + } catch (err: any) { + return Promise.reject(err); + } + }, }, }); diff --git a/src/types/http.d.ts b/src/types/http.d.ts index e59afc8..1f67f8e 100644 --- a/src/types/http.d.ts +++ b/src/types/http.d.ts @@ -22,6 +22,11 @@ export interface RequestTask { offHeadersReceived: () => void; onHeadersReceived: () => void; } +export interface CustomConfig { + auth?: boolean; + loading?: boolean; +} + export interface HttpRequestConfig extends Record { /** 请求基地址 */ baseURL?: string; @@ -59,7 +64,7 @@ export interface HttpRequestConfig extends Record { /** 设置响应的数据类型,支付宝小程序不支持 */ responseType?: 'text' | 'arraybuffer'; /** 自定义参数 */ - custom?: AnyObject; + custom?: CustomConfig; /** 超时时间,仅微信小程序(2.10.0)、支付宝小程序支持 */ timeout?: number; /** DNS解析时优先使用ipv4,仅 App-Android 支持 (HBuilderX 2.8.0+) */ @@ -108,7 +113,14 @@ export interface HttpInterceptorManager { forEach(h: any): void; } -export type InterceptorsRequest = HttpInterceptorManager; +export interface InterceptorsRequestConfig { + config: HttpRequestConfig; +} + +export type InterceptorsRequest = HttpInterceptorManager< + InterceptorsRequestConfig, + InterceptorsRequestConfig +>; export type InterceptorsResponse = HttpInterceptorManager; export interface Interceptors { diff --git a/src/utils/http/core/defaults.ts b/src/utils/http/core/defaults.ts index 6f0e309..ee32232 100644 --- a/src/utils/http/core/defaults.ts +++ b/src/utils/http/core/defaults.ts @@ -25,7 +25,7 @@ export default { // #ifdef APP-PLUS firstIpv4: false, // #endif - validateStatus: function validateStatus(status: Number) { + validateStatus: function validateStatus(status: number) { return status >= 200 && status < 300; }, } as HttpRequestConfig; diff --git a/src/utils/http/index.ts b/src/utils/http/index.ts index cc0b072..53afc20 100644 --- a/src/utils/http/index.ts +++ b/src/utils/http/index.ts @@ -1,5 +1,10 @@ import Request from './core/Request'; +import { getCache } from '@/utils/catch'; +import { TOKEN_KEY } from '@/enums/cacheEnum'; import { assign } from 'lodash-es'; +import { error } from '@/utils/log'; +import { HttpSuccess } from '@/types/http'; +import { Toast } from '@/utils/uniApi'; const BASE_URL = import.meta.env.VITE_BASE_URL; const HEADER = { @@ -7,71 +12,60 @@ const HEADER = { Accept: 'application/json, text/plain, */*', }; -const getTokenStorage = () => { - let token = ''; - try { - token = uni.getStorageSync('token'); - } catch (e) {} - return token; -}; +const TOKEN = () => getCache(TOKEN_KEY) || undefined; function createRequest() { return new Request({ baseURL: BASE_URL, header: HEADER, + custom: { + auth: true, + }, }); } -const defHttp = createRequest(); -// defHttp.setConfig((config) => { /* 设置全局配置 */ -// config.header = { -// ...config.header, -// a: 1, // 演示 -// b: 2 // 演示 -// } -// return config -// }) - +const request = createRequest(); /** * 请求拦截器 */ -defHttp.interceptors.request.use( - (config) => { - config.header = assign(config.header, { - token: getTokenStorage(), - }); - - console.log('interceptors.request', config); - /* - if (!token) { // 如果token不存在,return Promise.reject(config) 会取消本次请求 - return Promise.reject(config) - } - */ - return config; +request.interceptors.request.use( + (options) => { + const { config } = options; + const token = TOKEN(); + if (config.custom?.auth) { + if (!token) { + // token不存在跳转到登录页 + // return Promise.reject(options); + } + config.header = assign(config.header, { + authorization: `Bearer ${token}`, + }); + } + return options; }, - (config) => { - return Promise.reject(config); + (options) => { + return Promise.reject(options); }, ); /** * 响应拦截器 */ -defHttp.interceptors.response.use( - async (response) => { - /* 请求之后拦截器。可以使用async await 做异步操作 */ - // if (response.data.code !== 200) { // 服务端返回的状态码不等于200,则reject() - // return Promise.reject(response) - // } - console.log('响应===', response); - - return response; +request.interceptors.response.use( + async (response: HttpSuccess>) => { + const { data: resData } = response; + const { code, message, data } = resData; + if (code === 10000) { + return resData as any; + } + Toast(message); + return Promise.reject(resData); }, (response) => { // 请求错误做点什么。可以使用async await 做异步操作 - console.log(response); + error('Request Error!'); return Promise.reject(response); }, ); -export { defHttp }; +export { request }; diff --git a/src/utils/uniApi.ts b/src/utils/uniApi.ts new file mode 100644 index 0000000..4473aa5 --- /dev/null +++ b/src/utils/uniApi.ts @@ -0,0 +1,11 @@ +export function Toast(title: string, options?: Partial) { + uni.showToast({ + title: title, + duration: 1500, + icon: 'none', + ...options, + }); +} +export function hideToast() { + uni.hideToast(); +}