daShangDao_miniProgram/utils/request.js
2025-11-24 10:25:20 +08:00

124 lines
3.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.

// 引入配置文件
import config from './config.js';
/**
* 封装 uni.request 的通用请求方法
* @param {Object} options - 请求选项
* @param {string} options.url - 请求地址可以是相对路径会自动添加baseURL或完整URL
* @param {string} options.method - 请求方法默认为GET
* @param {Object} options.data - 请求数据
* @param {Object} options.header - 自定义请求头,会与默认请求头合并
* @param {boolean} options.loading - 是否显示加载提示默认为false
* @returns {Promise} - 返回Promise对象
*/
export default function request(options) {
return new Promise((resolve, reject) => {
// 开发环境使用mock数据
if (process.env.NODE_ENV === 'development' && options.mock) {
// 模拟微信登录接口
if (options.url === '/auth/login') {
return resolve({
code: 200,
data: {
token: 'mock-token-123',
openid: 'mock-openid',
access_token: 'mock-access-token',
userInfo: {
nickName: '测试用户',
avatarUrl: '/static/mock-avatar.png'
}
}
})
}
}
// 显示加载提示
if (options.loading) {
uni.showLoading({
title: '加载中...'
});
}
// 判断URL是否为完整URL以http开头如果不是则添加baseURL
const url = options.url.startsWith('http') ? options.url : config.baseURL + options.url;
// 合并默认请求头和自定义请求头
const header = {
...config.headers,
...options.header
};
// 如果有token添加到请求头
const token = uni.getStorageSync('token');
if (token) {
header['Authorization'] = token;
}
// 发起请求
uni.request({
url: url,
method: options.method || 'GET',
data: options.data,
header: header,
timeout: options.timeout || config.timeout,
success: (res) => {
// 隐藏加载提示
if (options.loading) {
uni.hideLoading();
}
// 处理响应
if (res.statusCode === 200) {
// 业务状态码处理
if (res.data.code === 200 || res.data.code === 0) {
resolve(res.data);
} else if (res.data.code === 401) {
// 未授权清除token并跳转到登录页
uni.removeStorageSync('token');
uni.showToast({
title: '登录已过期,请重新登录',
icon: 'none',
duration: 2000
});
setTimeout(() => {
uni.navigateTo({
url: '/pages/login/index'
});
}, 1000);
reject(res.data);
} else {
// 其他业务错误
uni.showToast({
title: res.data.msg || '请求失败',
icon: 'none',
duration: 2000
});
reject(res.data);
}
} else {
// HTTP状态码错误
uni.showToast({
title: `请求失败,状态码:${res.statusCode}`,
icon: 'none',
duration: 2000
});
reject(res.data);
}
},
fail: (err) => {
// 隐藏加载提示
if (options.loading) {
uni.hideLoading();
}
// 网络错误等
uni.showToast({
title: '网络请求失败',
icon: 'none',
duration: 2000
});
reject(err);
}
});
});
}