Files
threeonecheck_web/request/request.js
2026-02-08 09:30:43 +08:00

133 lines
4.6 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.

import Request from './luch-request/index.js';
// 基础的url
const baseUrl = 'https://yingji.hexieapi.com/prod-api';
// const baseUrl = 'http://192.168.1.168:5004';
const http = new Request({
baseURL: baseUrl,
timeout: 10000
})
// 动态获取 token从登录接口存储的
const getToken = () => {
const token = uni.getStorageSync('token');
return token ? `Bearer ${token}` : '';
};
// 请求之前查看是否为空
const isEmptyObject = (obj) => {
return Object.keys(obj).length === 0;
};
// 将对象转换为查询字符串
const objectToQueryString = (obj) => {
const keyValuePairs = [];
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
keyValuePairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
}
return keyValuePairs.join('&');
};
// 提示(延迟显示,避免和 hideLoading 冲突)
function showToast(title) {
setTimeout(() => {
uni.showToast({
title,
icon: 'none',
duration: 2000,
});
}, 100);
}
// 请求
const requestAPI = (config) => {
// 支持对象参数或传统参数
let { url, method = 'GET', data = {}, noAuth = false } = typeof config === 'object' && config.url ? config : { url: config, method: arguments[1] || 'GET', data: arguments[2] || {} };
if (method == 'GET' && !isEmptyObject(data)) {
url += '?' + objectToQueryString(data);
}
// 显示加载状态
uni.showLoading({
title: '加载中...'
});
// 构建 header登录等接口不需要 Authorization
const header = {
'Content-Type': 'application/json'
};
if (!noAuth) {
const token = getToken();
if (token) {
header['Authorization'] = token;
}
}
return new Promise((resolve, reject) => {
uni.request({
url: baseUrl + url,
method,
data,
header,
success: (res) => {
uni.hideLoading();
// 检查HTTP状态码
if (res.statusCode !== 200) {
console.error('HTTP错误:', res.statusCode);
// showToast(`请求失败 ${res.statusCode}`);
reject(`HTTP_${res.statusCode}`);
return;
}
// 检查业务状态码(如果后端有的话)
if (res.data && res.data.code !== undefined) {
// 支持 code === 200 或 code === 0 作为成功状态
if (res.data.code === 200 || res.data.code === 0 || res.code === 0) {
resolve(res.data);
} else if (res.data.code === 401) {
// token过期处理
uni.removeStorageSync('token');
uni.removeStorageSync('userInfo');
showToast('登录已过期,请重新登录');
setTimeout(() => {
uni.reLaunch({
url: '/pages/login/login'
});
}, 1500);
reject({ code: 401, msg: '登录已过期' });
} else {
// 支持多种错误信息字段msg、message、error
const errorMsg = res.data.msg || res.data.message || res.data.error || res.msg || '请求失败';
console.error('接口错误:', res.data); // 打印完整错误信息便于调试
showToast(errorMsg);
// reject 时传递完整错误信息,方便页面获取
reject({ code: res.data.code, msg: errorMsg, data: res.data });
}
} else {
// 没有业务状态码,直接返回数据
resolve(res.data);
}
},
fail: (err) => {
console.error('网络请求失败:', err);
uni.hideLoading();
// 区分不同的错误类型
if (err.errMsg && err.errMsg.includes('request:fail')) {
showToast('网络连接失败,请检查网络设置');
} else if (err.errMsg && err.errMsg.includes('timeout')) {
showToast('请求超时,请稍后重试');
} else {
showToast('网络异常,请稍后重试');
}
reject(err);
}
});
});
};
// 文件末尾应该导出
export { requestAPI, baseUrl, getToken };