0
# Network APIs
1
2
HTTP request functionality, file upload/download, WebSocket connections, and network status monitoring for Taro React Native applications.
3
4
## Capabilities
5
6
### HTTP Requests
7
8
Make HTTP requests with comprehensive configuration options and Promise support.
9
10
```typescript { .api }
11
/**
12
* Make an HTTP request
13
* @param options Request configuration options
14
* @returns RequestTask with abort capability
15
*/
16
function request<T = any>(options: {
17
url: string;
18
data?: any;
19
header?: Record<string, string>;
20
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'TRACE' | 'CONNECT';
21
dataType?: 'json' | 'text' | 'base64' | 'arraybuffer';
22
responseType?: 'text' | 'arraybuffer';
23
timeout?: number;
24
enableHttp2?: boolean;
25
enableQuic?: boolean;
26
enableCache?: boolean;
27
success?: (res: {
28
data: T;
29
statusCode: number;
30
header: Record<string, string>;
31
}) => void;
32
fail?: (res: TaroGeneral.CallbackResult) => void;
33
complete?: (res: any) => void;
34
}): Taro.RequestTask<T>;
35
36
interface RequestTask<T> extends Promise<{
37
data: T;
38
statusCode: number;
39
header: Record<string, string>;
40
}> {
41
/**
42
* Abort the request
43
*/
44
abort(): void;
45
}
46
```
47
48
**Usage Examples:**
49
50
```typescript
51
import { request } from "@tarojs/taro-rn";
52
53
// Simple GET request
54
const response = await request({
55
url: 'https://api.example.com/users',
56
method: 'GET'
57
});
58
console.log('Users:', response.data);
59
60
// POST request with data
61
const createResponse = await request({
62
url: 'https://api.example.com/users',
63
method: 'POST',
64
data: {
65
name: 'John Doe',
66
email: 'john@example.com'
67
},
68
header: {
69
'Content-Type': 'application/json'
70
}
71
});
72
73
// Request with custom headers and timeout
74
const authResponse = await request({
75
url: 'https://api.example.com/profile',
76
method: 'GET',
77
header: {
78
'Authorization': 'Bearer token123',
79
'Accept': 'application/json'
80
},
81
timeout: 10000
82
});
83
84
// Handle different response types
85
const imageResponse = await request({
86
url: 'https://example.com/image.jpg',
87
responseType: 'arraybuffer'
88
});
89
90
// Abortable request
91
const requestTask = request({
92
url: 'https://api.example.com/large-data',
93
timeout: 30000
94
});
95
96
// Abort after 5 seconds
97
setTimeout(() => {
98
requestTask.abort();
99
}, 5000);
100
101
try {
102
const result = await requestTask;
103
console.log('Request completed:', result);
104
} catch (error) {
105
console.log('Request aborted or failed:', error);
106
}
107
```
108
109
### File Upload
110
111
Upload files to remote servers with progress tracking.
112
113
```typescript { .api }
114
/**
115
* Upload files to a remote server
116
* @param options Upload configuration options
117
*/
118
function uploadFile(options: {
119
url: string;
120
filePath: string;
121
name: string;
122
header?: Record<string, string>;
123
formData?: Record<string, any>;
124
timeout?: number;
125
success?: (res: {
126
data: string;
127
statusCode: number;
128
}) => void;
129
fail?: (res: TaroGeneral.CallbackResult) => void;
130
complete?: (res: any) => void;
131
}): Taro.UploadTask;
132
133
interface UploadTask extends Promise<{
134
data: string;
135
statusCode: number;
136
}> {
137
/**
138
* Monitor upload progress
139
* @param callback Progress callback
140
*/
141
progress(callback: (res: {
142
progress: number;
143
totalBytesSent: number;
144
totalBytesExpectedToSend: number;
145
}) => void): void;
146
147
/**
148
* Abort the upload
149
*/
150
abort(): void;
151
}
152
```
153
154
### File Download
155
156
Download files from remote servers with progress tracking.
157
158
```typescript { .api }
159
/**
160
* Download files from a remote server
161
* @param options Download configuration options
162
*/
163
function downloadFile(options: {
164
url: string;
165
header?: Record<string, string>;
166
timeout?: number;
167
filePath?: string;
168
success?: (res: {
169
tempFilePath: string;
170
filePath?: string;
171
statusCode: number;
172
}) => void;
173
fail?: (res: TaroGeneral.CallbackResult) => void;
174
complete?: (res: any) => void;
175
}): Taro.DownloadTask;
176
177
interface DownloadTask extends Promise<{
178
tempFilePath: string;
179
filePath?: string;
180
statusCode: number;
181
}> {
182
/**
183
* Monitor download progress
184
* @param callback Progress callback
185
*/
186
progress(callback: (res: {
187
progress: number;
188
totalBytesWritten: number;
189
totalBytesExpectedToWrite: number;
190
}) => void): void;
191
192
/**
193
* Abort the download
194
*/
195
abort(): void;
196
}
197
```
198
199
**Usage Examples:**
200
201
```typescript
202
import { uploadFile, downloadFile } from "@tarojs/taro-rn";
203
204
// Upload file with progress tracking
205
const uploadTask = uploadFile({
206
url: 'https://api.example.com/upload',
207
filePath: '/path/to/local/file.jpg',
208
name: 'file',
209
formData: {
210
'user_id': '123',
211
'category': 'avatar'
212
}
213
});
214
215
uploadTask.progress((res) => {
216
console.log('Upload progress:', res.progress);
217
console.log('Bytes sent:', res.totalBytesSent);
218
});
219
220
const uploadResult = await uploadTask;
221
console.log('Upload complete:', uploadResult);
222
223
// Download file with progress tracking
224
const downloadTask = downloadFile({
225
url: 'https://example.com/file.pdf',
226
header: {
227
'Authorization': 'Bearer token123'
228
}
229
});
230
231
downloadTask.progress((res) => {
232
console.log('Download progress:', res.progress);
233
});
234
235
const downloadResult = await downloadTask;
236
console.log('Downloaded to:', downloadResult.tempFilePath);
237
```
238
239
### WebSocket Connection
240
241
Establish WebSocket connections for real-time communication.
242
243
```typescript { .api }
244
/**
245
* Connect to a WebSocket server
246
* @param options WebSocket connection options
247
*/
248
function connectSocket(options: {
249
url: string;
250
header?: Record<string, any>;
251
protocols?: string[];
252
timeout?: number;
253
success?: (res: TaroGeneral.CallbackResult) => void;
254
fail?: (res: TaroGeneral.CallbackResult) => void;
255
complete?: (res: any) => void;
256
}): Taro.SocketTask;
257
258
interface SocketTask {
259
/**
260
* Send data through the WebSocket
261
* @param options Send options
262
*/
263
send(options: {
264
data: string | ArrayBuffer;
265
success?: (res: TaroGeneral.CallbackResult) => void;
266
fail?: (res: TaroGeneral.CallbackResult) => void;
267
complete?: (res: any) => void;
268
}): void;
269
270
/**
271
* Close the WebSocket connection
272
* @param options Close options
273
*/
274
close(options?: {
275
code?: number;
276
reason?: string;
277
success?: (res: TaroGeneral.CallbackResult) => void;
278
fail?: (res: TaroGeneral.CallbackResult) => void;
279
complete?: (res: any) => void;
280
}): void;
281
282
/**
283
* Listen for WebSocket open event
284
* @param callback Open event callback
285
*/
286
onOpen(callback: (res: any) => void): void;
287
288
/**
289
* Listen for WebSocket close event
290
* @param callback Close event callback
291
*/
292
onClose(callback: (res: { code: number; reason: string }) => void): void;
293
294
/**
295
* Listen for WebSocket error event
296
* @param callback Error event callback
297
*/
298
onError(callback: (res: { errMsg: string }) => void): void;
299
300
/**
301
* Listen for WebSocket message event
302
* @param callback Message event callback
303
*/
304
onMessage(callback: (res: { data: string | ArrayBuffer }) => void): void;
305
}
306
```
307
308
**Usage Examples:**
309
310
```typescript
311
import { connectSocket } from "@tarojs/taro-rn";
312
313
// Connect to WebSocket
314
const socketTask = connectSocket({
315
url: 'wss://api.example.com/websocket',
316
header: {
317
'Authorization': 'Bearer token123'
318
}
319
});
320
321
// Set up event listeners
322
socketTask.onOpen((res) => {
323
console.log('WebSocket connected');
324
325
// Send initial message
326
socketTask.send({
327
data: JSON.stringify({ type: 'join', room: 'chat-room-1' })
328
});
329
});
330
331
socketTask.onMessage((res) => {
332
const message = JSON.parse(res.data as string);
333
console.log('Received message:', message);
334
});
335
336
socketTask.onError((res) => {
337
console.error('WebSocket error:', res.errMsg);
338
});
339
340
socketTask.onClose((res) => {
341
console.log('WebSocket closed:', res.code, res.reason);
342
});
343
344
// Send messages
345
socketTask.send({
346
data: JSON.stringify({
347
type: 'message',
348
content: 'Hello, world!'
349
})
350
});
351
352
// Close connection when done
353
socketTask.close({
354
code: 1000,
355
reason: 'Normal closure'
356
});
357
```
358
359
### Network Status
360
361
Monitor network connectivity and type.
362
363
```typescript { .api }
364
/**
365
* Get current network type
366
* @param options Network type options
367
*/
368
function getNetworkType(options?: {
369
success?: (res: {
370
networkType: 'wifi' | '2g' | '3g' | '4g' | '5g' | 'unknown' | 'none';
371
isConnected: boolean;
372
}) => void;
373
fail?: (res: TaroGeneral.CallbackResult) => void;
374
complete?: (res: any) => void;
375
}): Promise<{
376
networkType: 'wifi' | '2g' | '3g' | '4g' | '5g' | 'unknown' | 'none';
377
isConnected: boolean;
378
}>;
379
380
/**
381
* Listen to network status changes
382
* @param callback Network status change callback
383
*/
384
function onNetworkStatusChange(callback: (res: {
385
isConnected: boolean;
386
networkType: 'wifi' | '2g' | '3g' | '4g' | '5g' | 'unknown' | 'none';
387
}) => void): void;
388
389
/**
390
* Stop listening to network status changes
391
* @param callback Optional callback to remove specific listener
392
*/
393
function offNetworkStatusChange(callback?: (res: {
394
isConnected: boolean;
395
networkType: string;
396
}) => void): void;
397
```
398
399
**Usage Examples:**
400
401
```typescript
402
import {
403
getNetworkType,
404
onNetworkStatusChange,
405
offNetworkStatusChange
406
} from "@tarojs/taro-rn";
407
408
// Check current network status
409
const networkStatus = await getNetworkType();
410
console.log('Network type:', networkStatus.networkType);
411
console.log('Is connected:', networkStatus.isConnected);
412
413
// Adapt behavior based on network type
414
if (networkStatus.networkType === 'wifi') {
415
// High-quality content for WiFi
416
console.log('Load high-resolution images');
417
} else if (networkStatus.networkType === '2g' || networkStatus.networkType === '3g') {
418
// Optimized content for slower connections
419
console.log('Load compressed images');
420
}
421
422
// Listen for network changes
423
const networkChangeHandler = (res) => {
424
console.log('Network changed:', res.networkType, res.isConnected);
425
426
if (!res.isConnected) {
427
// Handle offline state
428
console.log('App is offline');
429
} else {
430
// Handle online state
431
console.log('App is back online');
432
}
433
};
434
435
onNetworkStatusChange(networkChangeHandler);
436
437
// Clean up listener when done
438
// offNetworkStatusChange(networkChangeHandler);
439
```