Files
WAI_Project_UNIX/utils/request.ts
2026-01-21 01:37:34 +08:00

53 lines
1.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { config } from "@/config";
import { auth } from "./auth";
/**
* 标准化请求工具
* 自动携带 Token并处理 401/1001 鉴权失效逻辑
*/
export function request(options: {
url: string;
method?: "GET" | "POST" | "PUT" | "DELETE";
data?: any;
header?: any;
}): Promise<any> {
let { url, method = "GET", data = {}, header = {} } = options;
// 拼接全路径
if (!url.startsWith("http")) {
url = config.baseUrl + url;
}
return new Promise((resolve, reject) => {
uni.request({
url,
method,
data,
header: {
Authorization: auth.getToken(),
...header
},
success: (res) => {
const resData = res.data as any;
// 业务成功 (code: 1000 为成功)
if (resData && resData.code === 1000) {
resolve(resData.data);
}
// 业务码 1001 或 HTTP 401 统一视为登录失效
else if (res.statusCode === 401 || (resData && resData.code === 1001)) {
// 仅清除状态,理由由调用方决定是否跳转
auth.logout();
reject(new Error("登录失效,请登录后重试"));
}
else {
reject(new Error(resData?.message || "服务器响应异常"));
}
},
fail: (err) => {
reject(new Error(err.errMsg || "网络请求失败"));
}
});
});
}