0
# HTTP Client Operations
1
2
Core fetch functionality for making HTTP requests with full Web Standards compatibility plus Node.js-specific enhancements like compression, redirect control, and HTTP agent configuration.
3
4
## Capabilities
5
6
### fetch Function
7
8
The main HTTP client function that performs network requests and returns a Promise resolving to a Response object.
9
10
```javascript { .api }
11
/**
12
* Perform an HTTP(S) fetch request
13
* @param url - URL string, URL object, or Request instance
14
* @param options - Request configuration options
15
* @returns Promise resolving to Response object
16
*/
17
function fetch(url: string | URL | Request, options?: RequestInit): Promise<Response>;
18
```
19
20
**Basic Usage:**
21
22
```javascript
23
import fetch from 'node-fetch';
24
25
// GET request
26
const response = await fetch('https://api.github.com/users/octocat');
27
const userData = await response.json();
28
29
// POST request
30
const postResponse = await fetch('https://httpbin.org/post', {
31
method: 'POST',
32
body: 'Hello World',
33
headers: { 'Content-Type': 'text/plain' }
34
});
35
```
36
37
### Request Configuration
38
39
The RequestInit interface provides comprehensive configuration options for HTTP requests.
40
41
```javascript { .api }
42
interface RequestInit {
43
// Standard Fetch API options
44
method?: string;
45
headers?: HeadersInit;
46
body?: BodyInit | null;
47
redirect?: 'follow' | 'error' | 'manual';
48
signal?: AbortSignal | null;
49
referrer?: string;
50
referrerPolicy?: ReferrerPolicy;
51
52
// Node.js specific extensions
53
agent?: http.Agent | ((parsedUrl: URL) => http.Agent);
54
compress?: boolean;
55
follow?: number;
56
size?: number;
57
highWaterMark?: number;
58
insecureHTTPParser?: boolean;
59
}
60
```
61
62
**Usage Examples:**
63
64
```javascript
65
// Request with custom headers and JSON body
66
const response = await fetch('https://api.example.com/data', {
67
method: 'POST',
68
headers: {
69
'Content-Type': 'application/json',
70
'Authorization': 'Bearer token123'
71
},
72
body: JSON.stringify({ name: 'John', age: 30 })
73
});
74
75
// Request with custom HTTP agent
76
import https from 'https';
77
78
const agent = new https.Agent({
79
keepAlive: true,
80
timeout: 30000
81
});
82
83
const response = await fetch('https://api.example.com/data', {
84
agent: agent
85
});
86
```
87
88
### HTTP Methods
89
90
Support for all standard HTTP methods through the method option.
91
92
```javascript { .api }
93
type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'PATCH';
94
```
95
96
**Usage Examples:**
97
98
```javascript
99
// Different HTTP methods
100
const getResponse = await fetch('https://api.example.com/users');
101
102
const postResponse = await fetch('https://api.example.com/users', {
103
method: 'POST',
104
body: JSON.stringify({ name: 'Alice' }),
105
headers: { 'Content-Type': 'application/json' }
106
});
107
108
const putResponse = await fetch('https://api.example.com/users/123', {
109
method: 'PUT',
110
body: JSON.stringify({ name: 'Alice Updated' }),
111
headers: { 'Content-Type': 'application/json' }
112
});
113
114
const deleteResponse = await fetch('https://api.example.com/users/123', {
115
method: 'DELETE'
116
});
117
```
118
119
### Request Body Types
120
121
Support for various body types including strings, buffers, streams, and form data.
122
123
```javascript { .api }
124
type BodyInit = Blob | Buffer | URLSearchParams | FormData | ReadableStream | string;
125
```
126
127
**Usage Examples:**
128
129
```javascript
130
// String body
131
await fetch('https://httpbin.org/post', {
132
method: 'POST',
133
body: 'Plain text content'
134
});
135
136
// JSON body
137
await fetch('https://httpbin.org/post', {
138
method: 'POST',
139
body: JSON.stringify({ key: 'value' }),
140
headers: { 'Content-Type': 'application/json' }
141
});
142
143
// Form data body
144
const formData = new FormData();
145
formData.append('field1', 'value1');
146
formData.append('field2', 'value2');
147
148
await fetch('https://httpbin.org/post', {
149
method: 'POST',
150
body: formData
151
});
152
153
// Stream body
154
import { createReadStream } from 'fs';
155
156
await fetch('https://httpbin.org/post', {
157
method: 'POST',
158
body: createReadStream('./file.txt'),
159
headers: { 'Content-Type': 'text/plain' }
160
});
161
```
162
163
### Redirect Handling
164
165
Control how redirects are handled during requests.
166
167
```javascript { .api }
168
type RedirectMode = 'follow' | 'error' | 'manual';
169
```
170
171
**Usage Examples:**
172
173
```javascript
174
// Follow redirects automatically (default)
175
const response = await fetch('https://github.com/node-fetch/node-fetch', {
176
redirect: 'follow'
177
});
178
179
// Throw error on redirect
180
try {
181
await fetch('https://github.com/node-fetch/node-fetch', {
182
redirect: 'error'
183
});
184
} catch (error) {
185
console.log('Redirect encountered:', error.message);
186
}
187
188
// Handle redirects manually
189
const response = await fetch('https://github.com/node-fetch/node-fetch', {
190
redirect: 'manual'
191
});
192
193
if (response.status >= 300 && response.status < 400) {
194
const location = response.headers.get('location');
195
console.log('Redirect to:', location);
196
}
197
```
198
199
### Request Timeout and Cancellation
200
201
Use AbortSignal to cancel requests or implement timeouts.
202
203
```javascript { .api }
204
interface AbortSignal {
205
readonly aborted: boolean;
206
addEventListener(type: 'abort', listener: () => void): void;
207
removeEventListener(type: 'abort', listener: () => void): void;
208
}
209
```
210
211
**Usage Examples:**
212
213
```javascript
214
// Request cancellation with AbortController
215
const controller = new AbortController();
216
const signal = controller.signal;
217
218
// Cancel request after 5 seconds
219
setTimeout(() => controller.abort(), 5000);
220
221
try {
222
const response = await fetch('https://api.example.com/slow-endpoint', {
223
signal: signal
224
});
225
} catch (error) {
226
if (error.name === 'AbortError') {
227
console.log('Request was cancelled');
228
}
229
}
230
231
// Request timeout helper
232
function fetchWithTimeout(url, options = {}, timeout = 5000) {
233
const controller = new AbortController();
234
const id = setTimeout(() => controller.abort(), timeout);
235
236
return fetch(url, {
237
...options,
238
signal: controller.signal
239
}).finally(() => clearTimeout(id));
240
}
241
```
242
243
### Node.js Specific Options
244
245
Advanced configuration options specific to Node.js environments.
246
247
```javascript { .api }
248
interface NodeRequestOptions {
249
agent?: http.Agent | ((parsedUrl: URL) => http.Agent);
250
compress?: boolean;
251
follow?: number;
252
size?: number;
253
highWaterMark?: number;
254
insecureHTTPParser?: boolean;
255
}
256
```
257
258
**Usage Examples:**
259
260
```javascript
261
// Custom compression settings
262
const response = await fetch('https://api.example.com/large-data', {
263
compress: false // Disable automatic decompression
264
});
265
266
// Custom redirect limit
267
const response = await fetch('https://example.com/redirect-chain', {
268
follow: 5 // Follow maximum 5 redirects
269
});
270
271
// Response size limit
272
const response = await fetch('https://api.example.com/large-file', {
273
size: 1024 * 1024 // Limit response to 1MB
274
});
275
276
// Custom stream buffer size
277
const response = await fetch('https://api.example.com/stream', {
278
highWaterMark: 64 * 1024 // 64KB buffer
279
});
280
```
281
282
### Default Headers
283
284
Headers automatically added by node-fetch when not explicitly provided.
285
286
```javascript { .api }
287
interface DefaultHeaders {
288
'Accept-Encoding': 'gzip, deflate, br'; // When compress: true
289
'Accept': '*/*';
290
'Content-Length': string; // Calculated automatically
291
'Host': string; // From target URL
292
'Transfer-Encoding': 'chunked'; // When body is stream
293
'User-Agent': 'node-fetch';
294
}
295
```
296
297
**Override defaults:**
298
299
```javascript
300
const response = await fetch('https://api.example.com/data', {
301
headers: {
302
'User-Agent': 'MyApp/1.0',
303
'Accept': 'application/json'
304
}
305
});
306
```