更新模板
This commit is contained in:
52
utils/request.ts
Normal file
52
utils/request.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
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 || "网络请求失败"));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user