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

request.md docs/

1
# Request Processing
2
3
Request object enhancements providing access to headers, query parameters, content negotiation, and request metadata analysis.
4
5
## Capabilities
6
7
### Header Access
8
9
Retrieve request headers with case-insensitive lookup.
10
11
```javascript { .api }
12
/**
13
* Get request header field value (case-insensitive)
14
* @param {string} name - Header field name
15
* @returns {string|undefined} Header value or undefined if not found
16
*/
17
get(name: string): string | undefined;
18
19
/**
20
* Alias for get() method
21
* @param {string} name - Header field name
22
* @returns {string|undefined} Header value or undefined if not found
23
*/
24
header(name: string): string | undefined;
25
```
26
27
**Usage Examples:**
28
29
```javascript
30
app.get('/api/data', (req, res) => {
31
// Get headers
32
const contentType = req.get('Content-Type');
33
const userAgent = req.header('User-Agent');
34
const authorization = req.get('authorization'); // Case insensitive
35
36
console.log('Content-Type:', contentType);
37
console.log('User-Agent:', userAgent);
38
39
res.json({ received: true });
40
});
41
```
42
43
### Content Negotiation
44
45
Determine the best response format based on client Accept headers.
46
47
```javascript { .api }
48
/**
49
* Check if given types are acceptable based on Accept header
50
* @param {string|string[]} types - MIME type(s) to check
51
* @returns {string|false} Best match or false if none acceptable
52
*/
53
accepts(types: string | string[]): string | false;
54
55
/**
56
* Check if given encodings are acceptable based on Accept-Encoding header
57
* @param {string|string[]} encodings - Encoding(s) to check
58
* @returns {string|false} Best match or false if none acceptable
59
*/
60
acceptsEncodings(encodings: string | string[]): string | false;
61
62
/**
63
* Check if given charsets are acceptable based on Accept-Charset header
64
* @param {string|string[]} charsets - Charset(s) to check
65
* @returns {string|false} Best match or false if none acceptable
66
*/
67
acceptsCharsets(charsets: string | string[]): string | false;
68
69
/**
70
* Check if given languages are acceptable based on Accept-Language header
71
* @param {string|string[]} langs - Language(s) to check
72
* @returns {string|false} Best match or false if none acceptable
73
*/
74
acceptsLanguages(langs: string | string[]): string | false;
75
```
76
77
**Usage Examples:**
78
79
```javascript
80
app.get('/api/data', (req, res) => {
81
// Content type negotiation
82
const format = req.accepts(['json', 'xml', 'html']);
83
84
switch (format) {
85
case 'json':
86
res.json({ data: 'JSON response' });
87
break;
88
case 'xml':
89
res.type('xml').send('<data>XML response</data>');
90
break;
91
case 'html':
92
res.send('<h1>HTML response</h1>');
93
break;
94
default:
95
res.status(406).send('Not Acceptable');
96
}
97
});
98
99
app.get('/compressed', (req, res) => {
100
// Check encoding support
101
if (req.acceptsEncodings('gzip')) {
102
// Send compressed response
103
res.set('Content-Encoding', 'gzip');
104
// ... compress and send
105
} else {
106
// Send uncompressed
107
}
108
});
109
```
110
111
### Request Analysis
112
113
Analyze request content and characteristics.
114
115
```javascript { .api }
116
/**
117
* Check if request contains given Content-Type
118
* @param {string|string[]} types - Content type(s) to check
119
* @returns {string|false} Matching type or false if no match
120
*/
121
is(types: string | string[]): string | false;
122
123
/**
124
* Parse Range header field
125
* @param {number} size - Total size of resource
126
* @param {object} options - Parsing options (optional)
127
* @returns {object|number} Parsed ranges or -1 if malformed, -2 if unsatisfiable
128
*/
129
range(size: number, options?: object): object | number;
130
```
131
132
**Usage Examples:**
133
134
```javascript
135
app.post('/upload', (req, res) => {
136
// Check content type
137
if (req.is('multipart/form-data')) {
138
// Handle file upload
139
} else if (req.is('application/json')) {
140
// Handle JSON data
141
} else {
142
res.status(415).send('Unsupported Media Type');
143
}
144
});
145
146
app.get('/video/:id', (req, res) => {
147
const videoSize = getVideoSize(req.params.id);
148
149
// Handle range requests for video streaming
150
const ranges = req.range(videoSize);
151
if (ranges && ranges !== -1 && ranges !== -2) {
152
// Send partial content
153
res.status(206);
154
// ... send range
155
} else {
156
// Send full video
157
res.status(200);
158
// ... send complete file
159
}
160
});
161
```
162
163
### Request Properties
164
165
Access various request metadata and parsed data.
166
167
```javascript { .api }
168
/**
169
* Parsed query string parameters
170
*/
171
query: { [key: string]: any };
172
173
/**
174
* Route parameters from URL path
175
*/
176
params: { [key: string]: string };
177
178
/**
179
* Request body (populated by body-parser middleware)
180
*/
181
body: any;
182
183
/**
184
* Request protocol ('http' or 'https')
185
*/
186
protocol: string;
187
188
/**
189
* True if protocol is https
190
*/
191
secure: boolean;
192
193
/**
194
* Remote IP address (respects trust proxy setting)
195
*/
196
ip: string;
197
198
/**
199
* Array of IP addresses when using proxy (trust proxy must be enabled)
200
*/
201
ips: string[];
202
203
/**
204
* Array of subdomains
205
*/
206
subdomains: string[];
207
208
/**
209
* Request URL pathname
210
*/
211
path: string;
212
213
/**
214
* Original request URL (before any internal redirects)
215
*/
216
originalUrl: string;
217
218
/**
219
* Base URL path on which app is mounted
220
*/
221
baseUrl: string;
222
223
/**
224
* Host header field with port number
225
*/
226
host: string;
227
228
/**
229
* Hostname without port number
230
*/
231
hostname: string;
232
233
/**
234
* True if request is fresh (cache validation)
235
*/
236
fresh: boolean;
237
238
/**
239
* True if request is stale (opposite of fresh)
240
*/
241
stale: boolean;
242
243
/**
244
* True if X-Requested-With header indicates XMLHttpRequest
245
*/
246
xhr: boolean;
247
248
/**
249
* Reference to the Express application instance
250
*/
251
app: Application;
252
253
/**
254
* Reference to the response object for this request
255
*/
256
res: Response;
257
258
/**
259
* Currently matched route object
260
*/
261
route: Route;
262
```
263
264
**Usage Examples:**
265
266
```javascript
267
app.get('/users/:id', (req, res) => {
268
// Route parameters
269
const userId = req.params.id;
270
271
// Query parameters
272
const page = req.query.page || 1;
273
const limit = req.query.limit || 10;
274
275
console.log(`Getting user ${userId}, page ${page}, limit ${limit}`);
276
277
res.json({ userId, page, limit });
278
});
279
280
app.post('/api/data', (req, res) => {
281
// Request body (requires body parser middleware)
282
const data = req.body;
283
284
// Request metadata
285
console.log('Protocol:', req.protocol);
286
console.log('Secure:', req.secure);
287
console.log('IP:', req.ip);
288
console.log('Hostname:', req.hostname);
289
console.log('Path:', req.path);
290
291
// Check if AJAX request
292
if (req.xhr) {
293
res.json({ message: 'AJAX request processed' });
294
} else {
295
res.redirect('/success');
296
}
297
});
298
299
app.get('/cache-demo', (req, res) => {
300
if (req.fresh) {
301
// Client cache is fresh, send 304
302
res.status(304).end();
303
} else {
304
// Send fresh content
305
res.set('ETag', '"12345"');
306
res.send('Fresh content');
307
}
308
});
309
310
// Subdomain routing
311
app.get('/', (req, res) => {
312
const subdomain = req.subdomains[0];
313
314
if (subdomain === 'api') {
315
res.json({ message: 'API subdomain' });
316
} else if (subdomain === 'admin') {
317
res.send('Admin panel');
318
} else {
319
res.send('Main site');
320
}
321
});
322
```
323
324
### Standard Node.js Properties
325
326
The Express request object extends Node.js IncomingMessage, providing access to all standard HTTP request properties:
327
328
```javascript { .api }
329
/**
330
* HTTP method (GET, POST, etc.)
331
*/
332
method: string;
333
334
/**
335
* Request URL string
336
*/
337
url: string;
338
339
/**
340
* HTTP headers object
341
*/
342
headers: { [key: string]: string | string[] };
343
344
/**
345
* HTTP version
346
*/
347
httpVersion: string;
348
349
/**
350
* Raw HTTP headers as array
351
*/
352
rawHeaders: string[];
353
```
354
355
**Usage Examples:**
356
357
```javascript
358
app.use((req, res, next) => {
359
// Log request details
360
console.log(`${req.method} ${req.url}`);
361
console.log('HTTP Version:', req.httpVersion);
362
console.log('Headers:', req.headers);
363
364
next();
365
});
366
```