npm-express

Description
Fast, unopinionated, minimalist web framework for Node.js
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-express@5.1.0

response.md docs/

1
# Response Generation
2
3
Response object enhancements for sending various types of responses, setting headers, managing cookies, and handling redirects.
4
5
## Capabilities
6
7
### Response Sending
8
9
Send responses with automatic content-type detection and format handling.
10
11
```javascript { .api }
12
/**
13
* Send response with automatic content-type detection
14
* @param {any} body - Response body (string, Buffer, object, array)
15
* @returns {Response} Response object for chaining
16
*/
17
send(body?: any): Response;
18
19
/**
20
* Send JSON response
21
* @param {any} obj - Object to serialize as JSON
22
* @returns {Response} Response object for chaining
23
*/
24
json(obj: any): Response;
25
26
/**
27
* Send JSON response with JSONP callback support
28
* @param {any} obj - Object to serialize as JSON
29
* @returns {Response} Response object for chaining
30
*/
31
jsonp(obj: any): Response;
32
33
/**
34
* Send status code with default message as response body
35
* @param {number} statusCode - HTTP status code
36
* @returns {Response} Response object for chaining
37
*/
38
sendStatus(statusCode: number): Response;
39
```
40
41
**Usage Examples:**
42
43
```javascript
44
app.get('/', (req, res) => {
45
// Send string response
46
res.send('Hello World!');
47
});
48
49
app.get('/api/users', (req, res) => {
50
// Send JSON response
51
res.json({
52
users: [
53
{ id: 1, name: 'Alice' },
54
{ id: 2, name: 'Bob' }
55
]
56
});
57
});
58
59
app.get('/jsonp-data', (req, res) => {
60
// Send JSONP response (checks for callback query parameter)
61
res.jsonp({ message: 'JSONP response' });
62
// If ?callback=myFunc, sends: myFunc({"message":"JSONP response"});
63
});
64
65
app.delete('/users/:id', (req, res) => {
66
// Send status with default message
67
res.sendStatus(204); // Sends "No Content"
68
});
69
70
app.get('/data', (req, res) => {
71
// send() handles different types automatically
72
res.send({ key: 'value' }); // Sets Content-Type: application/json
73
res.send('<h1>HTML</h1>'); // Sets Content-Type: text/html
74
res.send(Buffer.from('binary data')); // Sets Content-Type: application/octet-stream
75
});
76
```
77
78
### File Operations
79
80
Send files and handle file downloads.
81
82
```javascript { .api }
83
/**
84
* Transfer file at given path
85
* @param {string} path - File path
86
* @param {object} options - Transfer options (optional)
87
* @param {Function} callback - Callback function (optional)
88
*/
89
sendFile(path: string, options?: object, callback?: Function): void;
90
91
/**
92
* Transfer file as attachment (forces download)
93
* @param {string} path - File path
94
* @param {string} filename - Download filename (optional)
95
* @param {object} options - Transfer options (optional)
96
* @param {Function} callback - Callback function (optional)
97
*/
98
download(path: string, filename?: string, options?: object, callback?: Function): void;
99
```
100
101
**Usage Examples:**
102
103
```javascript
104
const path = require('path');
105
106
app.get('/files/:filename', (req, res) => {
107
const filename = req.params.filename;
108
const filePath = path.join(__dirname, 'uploads', filename);
109
110
// Send file with automatic content-type detection
111
res.sendFile(filePath, (err) => {
112
if (err) {
113
res.status(404).send('File not found');
114
}
115
});
116
});
117
118
app.get('/download/:filename', (req, res) => {
119
const filename = req.params.filename;
120
const filePath = path.join(__dirname, 'downloads', filename);
121
122
// Force download with custom filename
123
res.download(filePath, 'custom-name.pdf', (err) => {
124
if (err) {
125
res.status(404).send('File not found');
126
}
127
});
128
});
129
```
130
131
### Status and Headers
132
133
Manage HTTP status codes and response headers.
134
135
```javascript { .api }
136
/**
137
* Set HTTP status code
138
* @param {number} code - HTTP status code
139
* @returns {Response} Response object for chaining
140
*/
141
status(code: number): Response;
142
143
/**
144
* Set response header field
145
* @param {string} field - Header field name
146
* @param {string|string[]} val - Header value(s)
147
* @returns {Response} Response object for chaining
148
*/
149
set(field: string, val: string | string[]): Response;
150
151
/**
152
* Set multiple response header fields with object
153
* @param {object} fields - Object with header field names and values
154
* @returns {Response} Response object for chaining
155
*/
156
set(fields: { [key: string]: string | string[] }): Response;
157
158
/**
159
* Set response header field (alias for set)
160
* @param {string} field - Header field name
161
* @param {string|string[]} val - Header value(s)
162
* @returns {Response} Response object for chaining
163
*/
164
header(field: string, val: string | string[]): Response;
165
166
/**
167
* Set multiple response header fields with object (alias for set)
168
* @param {object} fields - Object with header field names and values
169
* @returns {Response} Response object for chaining
170
*/
171
header(fields: { [key: string]: string | string[] }): Response;
172
173
/**
174
* Get response header field value
175
* @param {string} field - Header field name
176
* @returns {string|undefined} Header value or undefined
177
*/
178
get(field: string): string | undefined;
179
180
/**
181
* Append additional header values
182
* @param {string} field - Header field name
183
* @param {string|string[]} val - Value(s) to append
184
* @returns {Response} Response object for chaining
185
*/
186
append(field: string, val: string | string[]): Response;
187
188
/**
189
* Add field to Vary header
190
* @param {string} field - Field name to add to Vary
191
* @returns {Response} Response object for chaining
192
*/
193
vary(field: string): Response;
194
```
195
196
**Usage Examples:**
197
198
```javascript
199
app.get('/api/data', (req, res) => {
200
// Set status and headers
201
res.status(200)
202
.set('Content-Type', 'application/json')
203
.set('X-API-Version', '1.0')
204
.json({ data: 'response' });
205
});
206
207
app.get('/custom-headers', (req, res) => {
208
// Multiple ways to set headers
209
res.header('X-Custom', 'value');
210
res.set({
211
'X-Multiple': 'header1',
212
'X-Another': 'header2'
213
});
214
215
// Append to existing headers
216
res.append('Set-Cookie', 'cookie1=value1');
217
res.append('Set-Cookie', 'cookie2=value2');
218
219
// Add to Vary header for caching
220
res.vary('User-Agent');
221
222
res.send('Response with custom headers');
223
});
224
```
225
226
### Content Type Management
227
228
Set and manage response content types.
229
230
```javascript { .api }
231
/**
232
* Set Content-Type HTTP header
233
* @param {string} type - MIME type or file extension
234
* @returns {Response} Response object for chaining
235
*/
236
type(type: string): Response;
237
238
/**
239
* Alias for type() method
240
* @param {string} type - MIME type or file extension
241
* @returns {Response} Response object for chaining
242
*/
243
contentType(type: string): Response;
244
245
/**
246
* Respond based on Accept header using callback object
247
* @param {object} obj - Object with content type keys and handler functions
248
* @returns {Response} Response object for chaining
249
*/
250
format(obj: object): Response;
251
```
252
253
**Usage Examples:**
254
255
```javascript
256
app.get('/api/data', (req, res) => {
257
res.type('json').send('{"message": "JSON string"}');
258
// Sets Content-Type: application/json
259
});
260
261
app.get('/file.xml', (req, res) => {
262
res.contentType('xml');
263
res.send('<root><data>XML content</data></root>');
264
});
265
266
app.get('/multi-format', (req, res) => {
267
// Respond with different formats based on Accept header
268
res.format({
269
'text/plain': () => {
270
res.send('Plain text response');
271
},
272
'text/html': () => {
273
res.send('<h1>HTML response</h1>');
274
},
275
'application/json': () => {
276
res.json({ message: 'JSON response' });
277
},
278
'default': () => {
279
res.status(406).send('Not Acceptable');
280
}
281
});
282
});
283
```
284
285
### Cookie Management
286
287
Set and clear HTTP cookies.
288
289
```javascript { .api }
290
/**
291
* Set cookie with name and value
292
* @param {string} name - Cookie name
293
* @param {any} value - Cookie value
294
* @param {object} options - Cookie options (optional)
295
* @returns {Response} Response object for chaining
296
*/
297
cookie(name: string, value: any, options?: object): Response;
298
299
/**
300
* Clear cookie by name
301
* @param {string} name - Cookie name
302
* @param {object} options - Cookie options (optional)
303
* @returns {Response} Response object for chaining
304
*/
305
clearCookie(name: string, options?: object): Response;
306
```
307
308
**Usage Examples:**
309
310
```javascript
311
app.post('/login', (req, res) => {
312
// Set authentication cookie
313
res.cookie('token', 'jwt-token-here', {
314
httpOnly: true,
315
secure: true,
316
maxAge: 86400000, // 24 hours
317
sameSite: 'strict'
318
});
319
320
res.json({ message: 'Logged in successfully' });
321
});
322
323
app.post('/logout', (req, res) => {
324
// Clear authentication cookie
325
res.clearCookie('token', {
326
httpOnly: true,
327
secure: true,
328
sameSite: 'strict'
329
});
330
331
res.json({ message: 'Logged out successfully' });
332
});
333
334
app.get('/preferences', (req, res) => {
335
// Set preference cookies
336
res.cookie('theme', 'dark');
337
res.cookie('language', 'en', { maxAge: 31536000000 }); // 1 year
338
339
res.send('Preferences saved');
340
});
341
```
342
343
### Navigation and Redirects
344
345
Handle URL redirections and set location headers.
346
347
```javascript { .api }
348
/**
349
* Set Location header
350
* @param {string} url - URL for Location header
351
* @returns {Response} Response object for chaining
352
*/
353
location(url: string): Response;
354
355
/**
356
* Redirect to URL with optional status code
357
* @param {string} url - Redirect URL
358
*/
359
redirect(url: string): void;
360
361
/**
362
* Redirect to URL with specific status code
363
* @param {number} status - HTTP status code (3xx)
364
* @param {string} url - Redirect URL
365
*/
366
redirect(status: number, url: string): void;
367
368
/**
369
* Set Content-Disposition header to attachment
370
* @param {string} filename - Attachment filename (optional)
371
* @returns {Response} Response object for chaining
372
*/
373
attachment(filename?: string): Response;
374
```
375
376
**Usage Examples:**
377
378
```javascript
379
app.post('/login', (req, res) => {
380
if (authenticateUser(req.body)) {
381
// Redirect to dashboard after successful login
382
res.redirect('/dashboard');
383
} else {
384
res.redirect(401, '/login?error=invalid');
385
}
386
});
387
388
app.get('/old-page', (req, res) => {
389
// Permanent redirect
390
res.redirect(301, '/new-page');
391
});
392
393
app.get('/download-report', (req, res) => {
394
// Set as downloadable attachment
395
res.attachment('monthly-report.pdf');
396
// Could follow with res.sendFile() or res.send()
397
});
398
399
app.get('/external-link', (req, res) => {
400
// Set location without redirecting
401
res.location('https://example.com');
402
res.send('Link available in Location header');
403
});
404
```
405
406
### Link Headers
407
408
Manage Link HTTP headers for resource relationships.
409
410
```javascript { .api }
411
/**
412
* Set Link header with given link object
413
* @param {object} links - Object with link relationships
414
* @returns {Response} Response object for chaining
415
*/
416
links(links: object): Response;
417
```
418
419
**Usage Examples:**
420
421
```javascript
422
app.get('/api/users', (req, res) => {
423
// Set pagination links
424
res.links({
425
next: '/api/users?page=2',
426
prev: '/api/users?page=1',
427
last: '/api/users?page=10'
428
});
429
430
res.json({ users: [], page: 1 });
431
});
432
```
433
434
### Template Rendering
435
436
Render view templates with local variables.
437
438
```javascript { .api }
439
/**
440
* Render view template with local variables
441
* @param {string} view - View name
442
* @param {object} locals - Local variables for template (optional)
443
* @param {Function} callback - Callback function (optional)
444
*/
445
render(view: string, locals?: object, callback?: Function): void;
446
```
447
448
**Usage Examples:**
449
450
```javascript
451
app.get('/', (req, res) => {
452
// Render template with data
453
res.render('index', {
454
title: 'Home Page',
455
user: req.user,
456
posts: getPosts()
457
});
458
});
459
460
app.get('/error', (req, res) => {
461
// Render with callback
462
res.render('error', { message: 'Something went wrong' }, (err, html) => {
463
if (err) {
464
res.status(500).send('Render error');
465
} else {
466
res.send(html);
467
}
468
});
469
});
470
```
471
472
### Response Properties
473
474
```javascript { .api }
475
/**
476
* Local variables scoped to the request, useful for exposing request-level information to templates
477
*/
478
locals: { [key: string]: any };
479
480
/**
481
* Reference to the Express application instance
482
*/
483
app: Application;
484
485
/**
486
* Reference to the request object for this response
487
*/
488
req: Request;
489
```
490
491
### Standard Node.js Properties
492
493
The Express response object extends Node.js ServerResponse, providing access to all standard HTTP response properties and methods:
494
495
```javascript { .api }
496
/**
497
* HTTP status code
498
*/
499
statusCode: number;
500
501
/**
502
* HTTP status message
503
*/
504
statusMessage: string;
505
506
/**
507
* Response headers object
508
*/
509
headers: { [key: string]: string | string[] };
510
511
/**
512
* True if headers have been sent
513
*/
514
headersSent: boolean;
515
```
516
517
**Usage Examples:**
518
519
```javascript
520
app.get('/status-check', (req, res) => {
521
console.log('Current status:', res.statusCode); // 200 (default)
522
console.log('Headers sent:', res.headersSent); // false
523
524
res.status(204).send();
525
526
console.log('Headers sent:', res.headersSent); // true
527
});
528
```