dingdanquanliucheng/frontend/mini-app/utils/request.js
2026-06-01 11:24:20 +08:00

51 lines
1.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.

/**
* 公共网络请求封装
* 职责:统一拼接 baseUrl、Authorization 头401 自动跳转登录。
*/
var auth = require("./auth");
/**
* @param {Object} options - 请求配置
* @param {string} options.url - 请求路径(不含基础 URL
* @param {string} [options.method] - HTTP 方法
* @param {Object} [options.data] - 请求体
* @param {Object} [options.header] - 额外请求头
* @returns {Promise<Object>} 解析后的响应数据
*/
function request(options) {
var app = getApp();
var token = auth.getToken();
return new Promise(function (resolve, reject) {
wx.request({
url: app.globalData.apiBaseUrl + options.url,
method: options.method || "GET",
data: options.data,
header: Object.assign(
{ "Content-Type": "application/json" },
token ? { Authorization: "Bearer " + token } : {},
options.header || {}
),
success: function (response) {
var result = response.data || {};
if (response.statusCode === 401) {
auth.logout();
wx.redirectTo({ url: "/pages/login/login" });
reject(new Error("登录已过期,请重新登录"));
return;
}
if (response.statusCode >= 400 || result.code !== 0) {
reject(new Error(result.message || "请求失败:" + response.statusCode));
return;
}
resolve(result.data);
},
fail: function () {
reject(new Error("网络请求失败,请检查网络"));
},
});
});
}
module.exports = request;