纳入 track-uniapp 前端项目 (扫码/任务树/记录/转交Picker)
This commit is contained in:
59
track-uniapp/utils/request.js
Normal file
59
track-uniapp/utils/request.js
Normal file
@ -0,0 +1,59 @@
|
||||
/**
|
||||
* uni.request 封装 — 统一的 HTTP 客户端
|
||||
* 自动携带 Token、401 跳转登录
|
||||
*/
|
||||
|
||||
const BASE_URL = "http://192.168.9.80:8011/api/v1";
|
||||
|
||||
export default function request(options) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const url = options.url.startsWith("http") ? options.url : BASE_URL + options.url;
|
||||
const token = uni.getStorageSync("token") || "";
|
||||
|
||||
uni.request({
|
||||
url,
|
||||
method: options.method || "GET",
|
||||
data: options.data || {},
|
||||
header: {
|
||||
"Content-Type": "application/json",
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
...(options.header || {}),
|
||||
},
|
||||
timeout: 15000,
|
||||
success(res) {
|
||||
const code = res.statusCode;
|
||||
if (code >= 200 && code < 300) {
|
||||
resolve(res.data);
|
||||
} else if (code === 401) {
|
||||
uni.removeStorageSync("token");
|
||||
uni.removeStorageSync("user");
|
||||
uni.showToast({ title: "登录已过期,请重新登录", icon: "none" });
|
||||
setTimeout(() => uni.reLaunch({ url: "/pages/login/login" }), 1000);
|
||||
reject(res);
|
||||
} else if (code === 400) {
|
||||
uni.showToast({ title: res.data?.detail || "请求参数有误", icon: "none", duration: 2500 });
|
||||
reject(res);
|
||||
} else {
|
||||
uni.showToast({ title: `请求失败 (${code})`, icon: "none" });
|
||||
reject(res);
|
||||
}
|
||||
},
|
||||
fail() {
|
||||
uni.showToast({ title: "网络连接失败", icon: "none" });
|
||||
reject(new Error("network"));
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function get(url, params = {}) {
|
||||
const query = Object.entries(params)
|
||||
.filter(([, v]) => v != null && v !== "")
|
||||
.map(([k, v]) => `${k}=${encodeURIComponent(v)}`)
|
||||
.join("&");
|
||||
return request({ url: query ? `${url}?${query}` : url, method: "GET" });
|
||||
}
|
||||
|
||||
export function post(url, data = {}) {
|
||||
return request({ url, method: "POST", data });
|
||||
}
|
||||
Reference in New Issue
Block a user