book-min/miniprogram/utils/request.ts

139 lines
3.3 KiB
TypeScript
Raw Normal View History

2024-12-18 16:15:08 +08:00
interface RequestHeader {
'Content-Type': string;
'Authorization'?: string;
[key: string]: string | undefined;
}
interface RequestOptions extends WechatMiniprogram.RequestOption {
loading?: boolean;
}
interface ResponseData<T = any> {
code: number;
message: string;
data: T;
time?: string;
}
const baseURL = 'http://localhost:8084/api';
const request = {
async request<T>(options: RequestOptions): Promise<ResponseData<T>> {
const token = wx.getStorageSync('token');
console.log(token);
// 定义header类型
const header: RequestHeader = {
'Content-Type': 'application/json',
...options.header,
};
// 统一添加token
if (token) {
console.log('Token值:', token);
header['Authorization'] = `Bearer ${token}`;
console.log('完整Authorization:', header['Authorization']);
}
if (options.loading) {
wx.showLoading({
title: '加载中...',
mask: true
});
}
try {
console.log('发送请求的header:', header);
const res = await new Promise<WechatMiniprogram.RequestSuccessCallbackResult>((resolve, reject) => {
wx.request({
url: baseURL + options.url,
method: options.method,
data: options.data,
header,
success: (res) => {
console.log('请求响应:', res);
// 先检查状态码
if (res.statusCode === 401) {
// 清除本地token
wx.removeStorageSync('token');
wx.removeStorageSync('userInfo');
// 跳转到登录页
wx.redirectTo({
url: '/pages/login/index'
});
reject(new Error('登录已过期,请重新登录'));
return;
}
resolve(res);
},
fail: reject
});
});
const data = res.data as ResponseData<T>;
// 检查业务状态码
if (data.code !== 200) {
throw new Error(data.message || '请求失败');
}
return data;
} catch (error) {
console.error('请求错误:', error);
// 统一错误提示
wx.showToast({
title: error instanceof Error ? error.message : '请求失败',
icon: 'none'
});
throw error;
} finally {
if (options.loading) {
wx.hideLoading();
}
}
},
// GET请求
get<T>(url: string, data?: object, options: Partial<RequestOptions> = {}): Promise<ResponseData<T>> {
return this.request<T>({
method: 'GET',
url,
data,
...options
});
},
// POST请求
post<T>(url: string, data?: object, options: Partial<RequestOptions> = {}): Promise<ResponseData<T>> {
return this.request<T>({
method: 'POST',
url,
data,
...options
});
},
// PUT请求
put<T>(url: string, data?: object, options: Partial<RequestOptions> = {}): Promise<ResponseData<T>> {
return this.request<T>({
method: 'PUT',
url,
data,
...options
});
},
// DELETE请求
delete<T>(url: string, data?: object, options: Partial<RequestOptions> = {}): Promise<ResponseData<T>> {
return this.request<T>({
method: 'DELETE',
url,
data,
...options
});
}
};
export default request;