http.ts
4.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/*
* @Description: 简单的HTTP请求工具,用于内部模块
* @version: 1.0.0
* @Author: limin
* @Date: 2025-01-27
*/
import { detectEnvironment, EnvironmentType } from './index';
/**
* HTTP响应接口
*/
interface HttpResponse<T = any> {
data: T;
statusCode: number;
}
/**
* 请求策略接口
*/
interface RequestStrategy {
get(url: string): Promise<any>;
}
/**
* UniApp请求策略
*/
class UniAppStrategy implements RequestStrategy {
async get(url: string): Promise<any> {
if (typeof uni === 'undefined' || !uni.request) {
throw new Error('UniApp环境不可用');
}
return new Promise((resolve, reject) => {
uni.request({
url,
method: 'GET',
success: (res: HttpResponse) => {
if (res.statusCode === 200) {
resolve(res.data);
} else {
reject(new Error(`请求失败: ${res.statusCode}`));
}
},
fail: (err: any) => {
reject(new Error(`请求失败: ${err.errMsg || err.message || '未知错误'}`));
}
});
});
}
}
/**
* 微信小程序请求策略
*/
class MiniProgramStrategy implements RequestStrategy {
async get(url: string): Promise<any> {
if (typeof wx === 'undefined' || !wx.request) {
throw new Error('微信小程序环境不可用');
}
return new Promise((resolve, reject) => {
wx.request({
url,
method: 'GET',
success: (res: HttpResponse) => {
if (res.statusCode === 200) {
resolve(res.data);
} else {
reject(new Error(`请求失败: ${res.statusCode}`));
}
},
fail: (err: any) => {
reject(new Error(`请求失败: ${err.errMsg || err.message || '未知错误'}`));
}
});
});
}
}
/**
* Web环境请求策略
*/
class WebStrategy implements RequestStrategy {
async get(url: string): Promise<any> {
// 优先使用 fetch
if (typeof fetch !== 'undefined') {
return this.fetchRequest(url);
}
// 备选使用 XMLHttpRequest
if (typeof XMLHttpRequest !== 'undefined') {
return this.xhrRequest(url);
}
throw new Error('当前环境不支持HTTP请求');
}
private async fetchRequest(url: string): Promise<any> {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
throw new Error(`Fetch请求失败: ${error instanceof Error ? error.message : '未知错误'}`);
}
}
private xhrRequest(url: string): Promise<any> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.timeout = 10000; // 10秒超时
xhr.onload = () => {
if (xhr.status === 200) {
try {
const data = JSON.parse(xhr.responseText);
resolve(data);
} catch (e) {
reject(new Error('响应数据解析失败'));
}
} else {
reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText || '请求失败'}`));
}
};
xhr.onerror = () => reject(new Error('网络请求失败'));
xhr.ontimeout = () => reject(new Error('请求超时'));
xhr.send();
});
}
}
/**
* 请求策略工厂
*/
class RequestStrategyFactory {
private static strategies = new Map<EnvironmentType, RequestStrategy>([
[EnvironmentType.UNIAPP, new UniAppStrategy()],
[EnvironmentType.MINIPROGRAM, new MiniProgramStrategy()],
[EnvironmentType.WEB, new WebStrategy()]
]);
static getStrategy(env: EnvironmentType): RequestStrategy {
const strategy = this.strategies.get(env);
if (!strategy) {
throw new Error(`不支持的环境类型: ${env}`);
}
return strategy;
}
}
/**
* 简单的HTTP GET请求函数,支持微信小程序、Web端和uniapp
* @param url 请求URL
* @returns Promise<any> 响应数据
*/
export async function simpleGet(url: string): Promise<any> {
if (!url || typeof url !== 'string') {
throw new Error('URL参数无效');
}
const env = detectEnvironment();
const strategy = RequestStrategyFactory.getStrategy(env);
return strategy.get(url);
}