0
# Request and Response Handling
1
2
Classes for creating and manipulating HTTP requests and responses with full Body interface support, providing complete control over HTTP communication.
3
4
## Capabilities
5
6
### Request Class
7
8
Represents an HTTP request with all necessary metadata and body content.
9
10
```javascript { .api }
11
/**
12
* HTTP Request class implementing the Body interface
13
*/
14
class Request {
15
constructor(input: string | URL | Request, init?: RequestInit);
16
17
// Properties (read-only)
18
readonly method: string;
19
readonly url: string;
20
readonly headers: Headers;
21
readonly redirect: 'follow' | 'error' | 'manual';
22
readonly signal: AbortSignal;
23
readonly referrer: string;
24
readonly referrerPolicy: string;
25
26
// Node.js extensions
27
readonly follow: number;
28
readonly compress: boolean;
29
readonly counter: number;
30
readonly agent: http.Agent | ((parsedUrl: URL) => http.Agent);
31
readonly highWaterMark: number;
32
readonly insecureHTTPParser: boolean;
33
34
// Methods
35
clone(): Request;
36
37
// Body interface methods
38
readonly body: ReadableStream | null;
39
readonly bodyUsed: boolean;
40
arrayBuffer(): Promise<ArrayBuffer>;
41
blob(): Promise<Blob>;
42
formData(): Promise<FormData>;
43
json(): Promise<any>;
44
text(): Promise<string>;
45
}
46
```
47
48
**Usage Examples:**
49
50
```javascript
51
import { Request } from 'node-fetch';
52
53
// Create request from URL
54
const request = new Request('https://api.github.com/users/octocat');
55
56
// Create request with options
57
const postRequest = new Request('https://httpbin.org/post', {
58
method: 'POST',
59
headers: { 'Content-Type': 'application/json' },
60
body: JSON.stringify({ name: 'Alice' })
61
});
62
63
// Clone request for reuse
64
const clonedRequest = postRequest.clone();
65
66
// Access request properties
67
console.log(request.url); // 'https://api.github.com/users/octocat'
68
console.log(request.method); // 'GET'
69
console.log(request.headers); // Headers object
70
71
// Use with fetch
72
const response = await fetch(request);
73
```
74
75
### Response Class
76
77
Represents an HTTP response with status information, headers, and body content.
78
79
```javascript { .api }
80
/**
81
* HTTP Response class implementing the Body interface
82
*/
83
class Response {
84
constructor(body?: BodyInit | null, init?: ResponseInit);
85
86
// Properties (read-only)
87
readonly status: number;
88
readonly statusText: string;
89
readonly ok: boolean;
90
readonly redirected: boolean;
91
readonly type: 'basic' | 'cors' | 'default' | 'error' | 'opaque' | 'opaqueredirect';
92
readonly url: string;
93
readonly headers: Headers;
94
95
// Methods
96
clone(): Response;
97
98
// Static methods
99
static redirect(url: string, status?: number): Response;
100
static error(): Response;
101
static json(data: any, init?: ResponseInit): Response;
102
103
// Body interface methods
104
readonly body: ReadableStream | null;
105
readonly bodyUsed: boolean;
106
arrayBuffer(): Promise<ArrayBuffer>;
107
blob(): Promise<Blob>;
108
formData(): Promise<FormData>;
109
json(): Promise<any>;
110
text(): Promise<string>;
111
}
112
```
113
114
**Usage Examples:**
115
116
```javascript
117
import fetch, { Response } from 'node-fetch';
118
119
// Standard fetch response
120
const response = await fetch('https://api.github.com/users/octocat');
121
122
// Check response status
123
if (response.ok) {
124
console.log('Success:', response.status);
125
} else {
126
console.error('Error:', response.status, response.statusText);
127
}
128
129
// Clone response for multiple reads
130
const clonedResponse = response.clone();
131
const text = await response.text();
132
const json = await clonedResponse.json();
133
134
// Create custom responses
135
const jsonResponse = Response.json({ message: 'Hello World' });
136
const redirectResponse = Response.redirect('https://example.com', 302);
137
const errorResponse = Response.error();
138
```
139
140
### ResponseInit Configuration
141
142
Configuration object for creating custom Response instances.
143
144
```javascript { .api }
145
interface ResponseInit {
146
status?: number;
147
statusText?: string;
148
headers?: HeadersInit;
149
}
150
```
151
152
**Usage Examples:**
153
154
```javascript
155
// Custom response with specific status
156
const customResponse = new Response('Custom content', {
157
status: 201,
158
statusText: 'Created',
159
headers: {
160
'Content-Type': 'text/plain',
161
'X-Custom-Header': 'value'
162
}
163
});
164
165
// JSON response with custom headers
166
const apiResponse = Response.json(
167
{ data: 'example', timestamp: Date.now() },
168
{
169
status: 200,
170
headers: {
171
'Cache-Control': 'no-cache',
172
'X-API-Version': '1.0'
173
}
174
}
175
);
176
```
177
178
### Request/Response Body Handling
179
180
Both Request and Response classes implement the Body interface for consistent body processing.
181
182
```javascript { .api }
183
interface Body {
184
readonly body: ReadableStream | null;
185
readonly bodyUsed: boolean;
186
187
arrayBuffer(): Promise<ArrayBuffer>;
188
blob(): Promise<Blob>;
189
formData(): Promise<FormData>;
190
json(): Promise<any>;
191
text(): Promise<string>;
192
}
193
```
194
195
**Usage Examples:**
196
197
```javascript
198
// Reading response body as different formats
199
const response = await fetch('https://api.github.com/users/octocat');
200
201
// As JSON (most common)
202
const userData = await response.json();
203
204
// As text
205
const htmlResponse = await fetch('https://example.com');
206
const htmlText = await htmlResponse.text();
207
208
// As ArrayBuffer for binary data
209
const imageResponse = await fetch('https://example.com/image.png');
210
const imageBuffer = await imageResponse.arrayBuffer();
211
212
// As Blob
213
const blob = await imageResponse.blob();
214
215
// Check if body has been consumed
216
console.log(response.bodyUsed); // true after calling json()
217
```
218
219
### Response Status Checking
220
221
Convenient properties for checking response success and handling errors.
222
223
```javascript { .api }
224
interface ResponseStatus {
225
readonly status: number; // HTTP status code (200, 404, etc.)
226
readonly statusText: string; // HTTP status message ('OK', 'Not Found', etc.)
227
readonly ok: boolean; // true for 200-299 status codes
228
readonly redirected: boolean; // true if response was redirected
229
}
230
```
231
232
**Usage Examples:**
233
234
```javascript
235
const response = await fetch('https://api.example.com/data');
236
237
// Check success status
238
if (response.ok) {
239
const data = await response.json();
240
console.log('Success:', data);
241
} else {
242
console.error(`HTTP Error: ${response.status} ${response.statusText}`);
243
}
244
245
// Handle specific status codes
246
switch (response.status) {
247
case 200:
248
console.log('Success');
249
break;
250
case 404:
251
console.log('Resource not found');
252
break;
253
case 500:
254
console.log('Server error');
255
break;
256
default:
257
console.log(`Unexpected status: ${response.status}`);
258
}
259
260
// Check if response was redirected
261
if (response.redirected) {
262
console.log('Final URL:', response.url);
263
}
264
```
265
266
### Request/Response Cloning
267
268
Create copies of Request or Response objects for reuse or multiple processing.
269
270
```javascript { .api }
271
interface Cloneable {
272
clone(): this;
273
}
274
```
275
276
**Usage Examples:**
277
278
```javascript
279
// Clone request for retry logic
280
const originalRequest = new Request('https://api.example.com/data', {
281
method: 'POST',
282
body: JSON.stringify({ data: 'important' })
283
});
284
285
async function fetchWithRetry(request, maxRetries = 3) {
286
for (let attempt = 1; attempt <= maxRetries; attempt++) {
287
try {
288
const clonedRequest = request.clone();
289
return await fetch(clonedRequest);
290
} catch (error) {
291
if (attempt === maxRetries) throw error;
292
console.log(`Retry ${attempt} failed, trying again...`);
293
}
294
}
295
}
296
297
// Clone response for multiple processing
298
const response = await fetch('https://api.example.com/data');
299
const response1 = response.clone();
300
const response2 = response.clone();
301
302
// Process same response data in different ways
303
const json = await response1.json();
304
const text = await response2.text();
305
```
306
307
### Static Response Methods
308
309
Utility methods for creating common response types.
310
311
```javascript { .api }
312
class Response {
313
/**
314
* Create a redirect response
315
* @param url - Redirect target URL
316
* @param status - HTTP redirect status code (default: 302)
317
*/
318
static redirect(url: string, status?: number): Response;
319
320
/**
321
* Create an error response
322
*/
323
static error(): Response;
324
325
/**
326
* Create a JSON response with automatic Content-Type header
327
* @param data - Data to serialize as JSON
328
* @param init - Additional response configuration
329
*/
330
static json(data: any, init?: ResponseInit): Response;
331
}
332
```
333
334
**Usage Examples:**
335
336
```javascript
337
// Create redirect responses
338
const tempRedirect = Response.redirect('https://new-location.com');
339
const permRedirect = Response.redirect('https://new-location.com', 301);
340
341
// Create error response
342
const errorResponse = Response.error();
343
console.log(errorResponse.status); // 0
344
console.log(errorResponse.ok); // false
345
346
// Create JSON responses
347
const apiResponse = Response.json({
348
status: 'success',
349
data: { id: 123, name: 'Example' },
350
timestamp: new Date().toISOString()
351
});
352
353
console.log(apiResponse.headers.get('Content-Type')); // 'application/json'
354
```