Files
midi-h5/until/request.js

53 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2025-08-11 11:51:38 +08:00
// src/utils/http.js
2025-09-02 16:28:18 +08:00
import config from './config.js';
2025-09-26 18:33:06 +08:00
const http = (options = {}) => {
console.log(options)
// 请求拦截器逻辑
const requestConfig = {
url: config.BASE_URL + options.url, // 拼接完整请求路径 :cite[1]:cite[2]:cite[7]
method: options.method || 'GET',
data: options.params || options.data || {},
header: { // 注意key 由 axios 的 `headers` 改为 uni.request 的 `header` :cite[1]
'Content-Type': 'application/json', // 明确设置 Content-Type因为 uni.request 默认可能使用 'application/x-www-form-urlencoded' :cite[1]
...options.header, // 合并自定义请求头
},
timeout: options.timeout || 5000,
sslVerify: false
};
2025-09-02 16:28:18 +08:00
2025-09-26 18:33:06 +08:00
// 在发送请求前可以执行的操作,例如添加 token :cite[1]:cite[7]:cite[8]
// 示例:添加 Token
const token = uni.getStorageSync('token');
if (token) {
requestConfig.header['Authorization'] = `${token}`; // 或根据你的后端要求调整
}
2025-08-14 11:26:34 +08:00
2025-09-26 18:33:06 +08:00
return new Promise((resolve, reject) => {
uni.request({
...requestConfig,
success: (response) => {
// 响应拦截器逻辑:对响应数据做点什么
// 这里根据你的业务需求调整,例如直接返回 data :cite[1]:cite[8]
resolve(response.data); // 注意uni.request 的响应结构 response.data 才是服务端返回的数据体 :cite[1]
},
fail: (error) => {
// 响应错误处理
reject(error);
}
});
});
};
2025-09-02 16:28:18 +08:00
2025-09-26 18:33:06 +08:00
// (可选)为方便使用,可以为不同的 HTTP 方法创建快捷方法 :cite[7]
['get', 'post', 'put', 'delete'].forEach((method) => {
http[method] = (url, data, options = {}) => {
return http({
url,
method: method.toUpperCase(),
data,
...options
});
};
});
2025-09-02 16:28:18 +08:00
2025-08-11 11:51:38 +08:00
export default http;