duidui_mini_program/utils/request.js
2026-03-27 10:41:46 +08:00

95 lines
2.4 KiB
JavaScript
Raw Permalink 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 apiConfig from '../config/api_config.js';
const request = (options) => {
return new Promise((resolve, reject) => {
const app = getApp();
// 使用统一的域名配置
const baseURL = apiConfig.fiberApiBaseURL;
// 获取token
const token = wx.getStorageSync('token');
// 构建请求头
const header = {
'Content-Type': 'application/json',
...options.header
};
// 如果有token添加到header
if (token) {
header.Authorization = `Bearer ${token}`;
}
wx.request({
url: `${baseURL}${options.url}`,
method: options.method || 'GET',
data: options.data,
header: header,
success: (res) => {
// 首先检查是否是401错误
if (res.statusCode === 401 || res.data.code === 401) {
// 清除登录信息
wx.removeStorageSync('token');
wx.removeStorageSync('userInfo');
// 立即跳转到登录页
wx.reLaunch({
url: '/pages/login/index'
});
reject(res.data);
return;
}
// 处理其他状态码
if (res.statusCode === 200) {
// 支持两种响应格式:
// 1. { code: 200, data: {...} } - 旧格式
// 2. { success: true, ... } - 新格式
// 3. 直接返回数据对象(如 OSS 凭证接口)
// 检查是否是直接返回数据的接口(如 OSS 凭证接口)
const isDirectDataResponse = options.url && (
options.url.includes('/oss/upload/signature')
);
// 如果是直接返回数据的接口,直接 resolve
if (isDirectDataResponse) {
resolve(res.data);
return;
}
if (res.data.code === 200 || res.data.success === true) {
resolve(res.data);
} else {
// 检查是否是获取进度接口,如果是则不显示错误提示(没有进度是正常情况)
const isProgressInfo = options.url && options.url.includes('/camp/progress/info');
if (!isProgressInfo) {
// 其他业务错误才显示提示
wx.showToast({
title: res.data.message || '请求失败',
icon: 'none'
});
}
// 无论是否显示提示,都 resolve让调用方自己处理
resolve(res.data);
}
} else {
// HTTP 状态码错误
wx.showToast({
title: '服务器错误',
icon: 'none'
});
reject(res);
}
},
fail: (err) => {
wx.showToast({
title: '网络错误',
icon: 'none'
});
reject(err);
}
});
});
};
export default request;