chore: 首次纳入版本控制(审查前基线,v1.2.0)
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
const { apiBase } = require("./config");
|
||||
|
||||
function token() {
|
||||
return wx.getStorageSync("ql_token") || "";
|
||||
}
|
||||
|
||||
/** 统一请求:成功返回 data,失败抛 {code, message, status}。 */
|
||||
function request(method, path, body) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const header = { "Content-Type": "application/json" };
|
||||
const t = token();
|
||||
if (t) header.Authorization = "Bearer " + t;
|
||||
|
||||
wx.request({
|
||||
url: apiBase + path,
|
||||
method,
|
||||
data: body || {},
|
||||
header,
|
||||
timeout: 15000,
|
||||
success(res) {
|
||||
const data = res.data || {};
|
||||
if (res.statusCode >= 200 && res.statusCode < 300 && data.ok) {
|
||||
resolve(data.data);
|
||||
return;
|
||||
}
|
||||
const err = (data && data.error) || {};
|
||||
if (res.statusCode === 401) {
|
||||
getApp().clearAuth();
|
||||
}
|
||||
reject({ code: err.code || "HTTP_" + res.statusCode, message: err.message || "请求失败", status: res.statusCode });
|
||||
},
|
||||
fail(e) {
|
||||
reject({
|
||||
code: "NETWORK",
|
||||
message: "连不上后端(" + apiBase + "):" + (e.errMsg || ""),
|
||||
});
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const get = (path) => request("GET", path);
|
||||
const post = (path, body) => request("POST", path, body);
|
||||
const patch = (path, body) => request("PATCH", path, body);
|
||||
const del = (path, body) => request("DELETE", path, body);
|
||||
|
||||
/** 失败时统一 toast,并把错误抛回去让调用方决定是否中断。 */
|
||||
function toastError(e) {
|
||||
wx.showToast({ title: (e && e.message) || "出错了", icon: "none", duration: 2500 });
|
||||
}
|
||||
|
||||
/** 没登录就去登录页。 */
|
||||
function requireLogin() {
|
||||
const app = getApp();
|
||||
if (!app.globalData.token) {
|
||||
wx.reLaunch({ url: "/pages/login/login" });
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 没孩子档案就去建档页。 */
|
||||
function requireChild() {
|
||||
if (!requireLogin()) return false;
|
||||
const app = getApp();
|
||||
if (!app.globalData.child) {
|
||||
wx.reLaunch({ url: "/pages/children/children" });
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
module.exports = { request, get, post, patch, del, toastError, requireLogin, requireChild, token };
|
||||
@@ -0,0 +1,5 @@
|
||||
// 后端地址。开发时用本机(开发者工具里要勾「不校验合法域名」);
|
||||
// 上线前改成你自己的 https 域名,并在小程序后台把它加进 request 合法域名。
|
||||
module.exports = {
|
||||
apiBase: "http://127.0.0.1:8000",
|
||||
};
|
||||
Reference in New Issue
Block a user