117 lines
2.6 KiB
JavaScript
117 lines
2.6 KiB
JavaScript
const { apiBase } = require("./config");
|
|
|
|
function getToken() {
|
|
return wx.getStorageSync("auth_token") || "";
|
|
}
|
|
|
|
function clearSession() {
|
|
wx.removeStorageSync("auth_token");
|
|
wx.removeStorageSync("auth_user");
|
|
}
|
|
|
|
function request(path, options = {}) {
|
|
const token = getToken();
|
|
const headers = Object.assign({}, options.headers || {});
|
|
if (token) headers.Authorization = `Bearer ${token}`;
|
|
|
|
return new Promise((resolve, reject) => {
|
|
wx.request({
|
|
url: `${apiBase}${path}`,
|
|
method: options.method || "GET",
|
|
data: options.data,
|
|
header: headers,
|
|
success(res) {
|
|
if (res.statusCode === 401) {
|
|
clearSession();
|
|
wx.navigateTo({ url: "/pages/bind/index" });
|
|
reject(new Error("登录已过期"));
|
|
return;
|
|
}
|
|
if (res.statusCode >= 400) {
|
|
const message = res.data?.detail || res.data?.message || "操作失败";
|
|
reject(new Error(message));
|
|
return;
|
|
}
|
|
resolve(res.data);
|
|
},
|
|
fail() {
|
|
reject(new Error("网络连接失败"));
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
function get(path, data) {
|
|
return request(path, { data });
|
|
}
|
|
|
|
function post(path, data) {
|
|
return request(path, {
|
|
method: "POST",
|
|
data,
|
|
headers: { "Content-Type": "application/json" }
|
|
});
|
|
}
|
|
|
|
function postForm(path, data) {
|
|
return request(path, {
|
|
method: "POST",
|
|
data,
|
|
headers: { "Content-Type": "application/x-www-form-urlencoded" }
|
|
});
|
|
}
|
|
|
|
function put(path, data) {
|
|
return request(path, {
|
|
method: "PUT",
|
|
data,
|
|
headers: { "Content-Type": "application/json" }
|
|
});
|
|
}
|
|
|
|
function del(path) {
|
|
return request(path, { method: "DELETE" });
|
|
}
|
|
|
|
function uploadFile(path, filePath, formData = {}, fieldName = "files") {
|
|
const token = getToken();
|
|
return new Promise((resolve, reject) => {
|
|
wx.uploadFile({
|
|
url: `${apiBase}${path}`,
|
|
filePath,
|
|
name: fieldName,
|
|
formData,
|
|
header: token ? { Authorization: `Bearer ${token}` } : {},
|
|
success(res) {
|
|
if (res.statusCode >= 400) {
|
|
let message = "上传失败";
|
|
try {
|
|
const data = JSON.parse(res.data || "{}");
|
|
message = data.detail || data.message || message;
|
|
} catch {}
|
|
reject(new Error(message));
|
|
return;
|
|
}
|
|
try {
|
|
resolve(JSON.parse(res.data || "{}"));
|
|
} catch {
|
|
resolve({});
|
|
}
|
|
},
|
|
fail: () => reject(new Error("上传失败"))
|
|
});
|
|
});
|
|
}
|
|
|
|
module.exports = {
|
|
clearSession,
|
|
del,
|
|
get,
|
|
getToken,
|
|
post,
|
|
postForm,
|
|
put,
|
|
uploadFile,
|
|
request
|
|
};
|