Files
track/track-uniapp/utils/request.js

75 lines
2.5 KiB
JavaScript
Raw 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.

/**
* uni.request 封装 — 生产环境(服务器 172.16.0.198
* 打包 APK 前:将 request.prod.js 重命名为 request.js 替换原文件
*/
const BASE_URL = "http://172.16.0.198: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 === 403) {
uni.showToast({ title: res.data?.detail || "无权操作", icon: "none", duration: 3000 });
reject(res);
} else if (code === 400) {
uni.showToast({ title: res.data?.detail || "请求参数有误", icon: "none", duration: 2500 });
reject(res);
} else if (code === 409) {
uni.showToast({ title: res.data?.detail || "操作冲突", icon: "none", duration: 3000 });
reject(res);
} else {
const detail = res.data?.detail || "";
uni.showToast({ title: detail ? `${detail}` : `请求失败 (${code})`, icon: "none", duration: 3000 });
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 });
}
export function patch(url, data = {}) {
return request({ url, method: "PATCH", data });
}
export function put(url, data = {}) {
return request({ url, method: "PUT", data });
}