0
# Response Handling
1
2
Response object properties and methods for accessing response data, headers, and metadata with comprehensive parsing and error handling capabilities.
3
4
## Capabilities
5
6
### Response Properties
7
8
Core properties available on response objects returned from requests.
9
10
```javascript { .api }
11
/**
12
* Response object properties
13
*/
14
interface Response {
15
/** HTTP status code (e.g., 200, 404, 500) */
16
status: number;
17
18
/** HTTP status code (alias for status) */
19
statusCode: number;
20
21
/** Raw response body as string */
22
text: string;
23
24
/** Parsed response body (JSON, form data, etc.) */
25
body: any;
26
27
/** Response headers object (lowercase keys) */
28
header: object;
29
30
/** Content type without parameters */
31
type: string;
32
33
/** Character encoding (e.g., 'utf8') */
34
charset: string;
35
36
/** Array of redirect URLs if redirects occurred */
37
redirects: string[];
38
39
/** Files object for multipart responses */
40
files?: object;
41
42
/** Links header parsed into object */
43
links: object;
44
45
/** Response status type (1-5, representing 1xx, 2xx, etc.) */
46
statusType: number;
47
48
/** Boolean status flags */
49
info: boolean; // 1xx status codes
50
ok: boolean; // 2xx status codes
51
redirect: boolean; // 3xx status codes
52
clientError: boolean; // 4xx status codes
53
serverError: boolean; // 5xx status codes
54
error: boolean | Error; // 4xx or 5xx status codes
55
56
/** Specific status code flags */
57
created: boolean; // 201
58
accepted: boolean; // 202
59
noContent: boolean; // 204
60
badRequest: boolean; // 400
61
unauthorized: boolean; // 401
62
forbidden: boolean; // 403
63
notFound: boolean; // 404
64
notAcceptable: boolean; // 406
65
unprocessableEntity: boolean; // 422
66
}
67
```
68
69
**Usage Examples:**
70
71
```javascript
72
const superagent = require('superagent');
73
74
const response = await superagent.get('https://api.example.com/users');
75
76
// Status information
77
console.log('Status:', response.status); // 200
78
console.log('Status:', response.statusCode); // 200 (alias)
79
80
// Response body
81
console.log('Raw text:', response.text); // Raw response string
82
console.log('Parsed body:', response.body); // Parsed JSON/XML/etc
83
84
// Headers
85
console.log('All headers:', response.header);
86
console.log('Content-Type:', response.header['content-type']);
87
88
// Content information
89
console.log('Content type:', response.type); // 'application/json'
90
console.log('Charset:', response.charset); // 'utf8'
91
92
// Redirect information
93
if (response.redirects.length > 0) {
94
console.log('Redirected through:', response.redirects);
95
}
96
97
// Status flags and classifications
98
console.log('Status type:', response.statusType); // 2 (for 2xx)
99
console.log('Is success:', response.ok); // true for 2xx
100
console.log('Is redirect:', response.redirect); // true for 3xx
101
console.log('Is client error:', response.clientError); // true for 4xx
102
console.log('Is server error:', response.serverError); // true for 5xx
103
console.log('Has error:', !!response.error); // true for 4xx/5xx
104
105
// Specific status code flags
106
if (response.created) {
107
console.log('Resource was created (201)');
108
}
109
if (response.noContent) {
110
console.log('No content returned (204)');
111
}
112
if (response.notFound) {
113
console.log('Resource not found (404)');
114
}
115
if (response.unauthorized) {
116
console.log('Authentication required (401)');
117
}
118
```
119
120
### Response Methods
121
122
Methods available on response objects for accessing specific data.
123
124
```javascript { .api }
125
/**
126
* Get response header field value (case-insensitive)
127
* @param {string} field - Header field name
128
* @returns {string} Header field value
129
*/
130
Response.prototype.get(field): string;
131
132
/**
133
* Create an Error object from the response for error handling
134
* @returns {Error} Error object with response details
135
*/
136
Response.prototype.toError(): Error;
137
```
138
139
**Usage Examples:**
140
141
```javascript
142
const response = await superagent.get('https://api.example.com/data');
143
144
// Get specific headers (case-insensitive)
145
console.log('Content-Type:', response.get('Content-Type'));
146
console.log('content-type:', response.get('content-type')); // Same result
147
console.log('Authorization:', response.get('authorization'));
148
149
// Common headers
150
console.log('Cache-Control:', response.get('Cache-Control'));
151
console.log('ETag:', response.get('ETag'));
152
console.log('Last-Modified:', response.get('Last-Modified'));
153
154
// Convert response to error (useful for error status codes)
155
if (response.error) {
156
const errorObj = response.toError();
157
console.log('Error message:', errorObj.message);
158
console.log('Error status:', errorObj.status);
159
}
160
```
161
162
### Response Body Parsing
163
164
Automatic parsing based on content type with support for various formats.
165
166
```javascript
167
// JSON responses
168
const jsonResponse = await superagent.get('https://api.example.com/users.json');
169
console.log('Users:', jsonResponse.body.users); // Automatically parsed JSON
170
171
// XML responses (if parser is configured)
172
const xmlResponse = await superagent.get('https://api.example.com/data.xml');
173
console.log('XML body:', xmlResponse.body);
174
175
// Form-encoded responses
176
const formResponse = await superagent.get('https://api.example.com/form-data');
177
console.log('Form data:', formResponse.body);
178
179
// Binary responses
180
const binaryResponse = await superagent
181
.get('https://api.example.com/file.pdf')
182
.responseType('blob'); // Browser
183
console.log('Binary data:', binaryResponse.body);
184
185
// Text responses
186
const textResponse = await superagent.get('https://api.example.com/plain.txt');
187
console.log('Text content:', textResponse.text);
188
console.log('Also available as body:', textResponse.body);
189
```
190
191
### Error Response Handling
192
193
Handle error responses with detailed information.
194
195
```javascript
196
try {
197
const response = await superagent.get('https://api.example.com/data');
198
console.log('Success:', response.body);
199
} catch (err) {
200
// Error responses still have response object
201
if (err.response) {
202
console.log('Error status:', err.response.status);
203
console.log('Error body:', err.response.body);
204
console.log('Error text:', err.response.text);
205
console.log('Error headers:', err.response.header);
206
207
// Handle specific error codes
208
switch (err.response.status) {
209
case 400:
210
console.log('Bad request:', err.response.body.message);
211
break;
212
case 401:
213
console.log('Unauthorized - check credentials');
214
break;
215
case 404:
216
console.log('Resource not found');
217
break;
218
case 500:
219
console.log('Server error:', err.response.body.error);
220
break;
221
default:
222
console.log('Unexpected error:', err.response.status);
223
}
224
} else {
225
// Network or other errors without response
226
console.error('Network error:', err.message);
227
}
228
}
229
```
230
231
### Response Status Checking
232
233
Check response status and handle different scenarios.
234
235
```javascript
236
const response = await superagent
237
.get('https://api.example.com/data')
238
.ok(res => res.status < 500); // Don't throw on 4xx errors
239
240
// Check status ranges
241
if (response.status >= 200 && response.status < 300) {
242
console.log('Success response');
243
} else if (response.status >= 300 && response.status < 400) {
244
console.log('Redirect response');
245
} else if (response.status >= 400 && response.status < 500) {
246
console.log('Client error');
247
} else if (response.status >= 500) {
248
console.log('Server error');
249
}
250
251
// Check specific status codes
252
switch (response.status) {
253
case 200:
254
console.log('OK');
255
break;
256
case 201:
257
console.log('Created');
258
break;
259
case 204:
260
console.log('No Content');
261
break;
262
case 304:
263
console.log('Not Modified');
264
break;
265
}
266
```
267
268
### Headers Analysis
269
270
Analyze and use response headers for various purposes.
271
272
```javascript
273
const response = await superagent.get('https://api.example.com/data');
274
275
// Content information
276
const contentType = response.get('Content-Type');
277
const contentLength = response.get('Content-Length');
278
const encoding = response.get('Content-Encoding');
279
280
console.log(`Received ${contentLength} bytes of ${contentType}`);
281
if (encoding) {
282
console.log(`Content encoded with: ${encoding}`);
283
}
284
285
// Caching headers
286
const cacheControl = response.get('Cache-Control');
287
const etag = response.get('ETag');
288
const lastModified = response.get('Last-Modified');
289
290
if (cacheControl) {
291
console.log('Cache policy:', cacheControl);
292
}
293
294
// Security headers
295
const securityHeaders = [
296
'X-Content-Type-Options',
297
'X-Frame-Options',
298
'X-XSS-Protection',
299
'Strict-Transport-Security'
300
];
301
302
securityHeaders.forEach(header => {
303
const value = response.get(header);
304
if (value) {
305
console.log(`${header}: ${value}`);
306
}
307
});
308
309
// Custom application headers
310
const requestId = response.get('X-Request-ID');
311
const rateLimit = response.get('X-RateLimit-Remaining');
312
313
if (requestId) {
314
console.log('Request ID:', requestId);
315
}
316
if (rateLimit) {
317
console.log('Rate limit remaining:', rateLimit);
318
}
319
```
320
321
### Multipart Response Handling
322
323
Handle multipart responses with files and form data.
324
325
```javascript
326
const response = await superagent
327
.post('https://api.example.com/upload')
328
.attach('file', '/path/to/file.txt')
329
.field('title', 'My File');
330
331
// Access form fields
332
console.log('Response body:', response.body);
333
334
// Access uploaded files (if server returns file info)
335
if (response.files) {
336
console.log('Files processed:', response.files);
337
}
338
339
// Parse multipart response
340
const multipartResponse = await superagent
341
.get('https://api.example.com/multipart-data')
342
.buffer(true);
343
344
if (multipartResponse.files) {
345
Object.keys(multipartResponse.files).forEach(fieldName => {
346
const file = multipartResponse.files[fieldName];
347
console.log(`File ${fieldName}:`, {
348
name: file.name,
349
size: file.size,
350
type: file.type
351
});
352
});
353
}
354
```
355
356
### Response Streaming
357
358
Handle streamed responses for large data.
359
360
```javascript
361
const fs = require('fs');
362
363
// Stream response to file
364
const request = superagent.get('https://api.example.com/large-file.zip');
365
const writeStream = fs.createWriteStream('/path/to/output.zip');
366
367
request.pipe(writeStream);
368
369
// Handle streaming events
370
request.on('response', (res) => {
371
console.log('Response started:', res.status);
372
console.log('Content-Length:', res.get('Content-Length'));
373
});
374
375
request.on('progress', (event) => {
376
console.log(`Downloaded: ${event.loaded}/${event.total} bytes`);
377
});
378
379
writeStream.on('finish', () => {
380
console.log('Download completed');
381
});
382
383
writeStream.on('error', (err) => {
384
console.error('Download failed:', err);
385
});
386
```
387
388
### Response Processing Patterns
389
390
Common patterns for processing responses.
391
392
```javascript
393
// Paginated response handling
394
async function fetchAllPages(baseUrl) {
395
const allData = [];
396
let nextUrl = baseUrl;
397
398
while (nextUrl) {
399
const response = await superagent.get(nextUrl);
400
401
allData.push(...response.body.data);
402
403
// Check for pagination info in headers or body
404
const linkHeader = response.get('Link');
405
nextUrl = parseLinkHeader(linkHeader)?.next;
406
407
// Or check response body for next page
408
// nextUrl = response.body.pagination?.next_url;
409
}
410
411
return allData;
412
}
413
414
// Response validation
415
function validateResponse(response) {
416
// Check content type
417
const contentType = response.get('Content-Type');
418
if (!contentType || !contentType.includes('application/json')) {
419
throw new Error('Expected JSON response');
420
}
421
422
// Check required fields
423
if (!response.body.data) {
424
throw new Error('Missing required data field');
425
}
426
427
// Validate response structure
428
if (typeof response.body.data !== 'object') {
429
throw new Error('Invalid data format');
430
}
431
432
return response.body;
433
}
434
435
// Usage
436
try {
437
const response = await superagent.get('https://api.example.com/data');
438
const validatedData = validateResponse(response);
439
console.log('Valid data:', validatedData);
440
} catch (err) {
441
console.error('Validation failed:', err.message);
442
}
443
```
444
445
### Response Caching
446
447
Implement response caching based on headers.
448
449
```javascript
450
const responseCache = new Map();
451
452
async function cachedRequest(url) {
453
// Check cache first
454
const cached = responseCache.get(url);
455
if (cached && !isCacheExpired(cached)) {
456
console.log('Using cached response');
457
return cached.response;
458
}
459
460
// Make request with cache headers
461
const request = superagent.get(url);
462
463
if (cached) {
464
// Add conditional request headers
465
if (cached.etag) {
466
request.set('If-None-Match', cached.etag);
467
}
468
if (cached.lastModified) {
469
request.set('If-Modified-Since', cached.lastModified);
470
}
471
}
472
473
try {
474
const response = await request;
475
476
// Cache the response
477
responseCache.set(url, {
478
response: response,
479
etag: response.get('ETag'),
480
lastModified: response.get('Last-Modified'),
481
cacheControl: response.get('Cache-Control'),
482
timestamp: Date.now()
483
});
484
485
return response;
486
487
} catch (err) {
488
if (err.status === 304) {
489
// Not modified, return cached version
490
console.log('Resource not modified, using cache');
491
return cached.response;
492
}
493
throw err;
494
}
495
}
496
497
function isCacheExpired(cached) {
498
if (cached.cacheControl) {
499
const maxAge = extractMaxAge(cached.cacheControl);
500
if (maxAge && Date.now() - cached.timestamp > maxAge * 1000) {
501
return true;
502
}
503
}
504
return false;
505
}
506
```