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@4.21.0

routing.md docs/

1
# HTTP Routing
2
3
Route definition and HTTP method handling for creating RESTful APIs and web applications with pattern matching and parameter extraction.
4
5
## Capabilities
6
7
### HTTP Method Routing
8
9
Handle specific HTTP methods with route patterns and middleware functions.
10
11
```javascript { .api }
12
/**
13
* Handle GET requests to specified path
14
* @param {string} path - Route path pattern
15
* @param {...RequestHandler} handlers - Route handler functions
16
* @returns {Application} Application instance for chaining
17
*/
18
app.get(path: string, ...handlers: RequestHandler[]): Application;
19
20
/**
21
* Handle POST requests to specified path
22
* @param {string} path - Route path pattern
23
* @param {...RequestHandler} handlers - Route handler functions
24
* @returns {Application} Application instance for chaining
25
*/
26
app.post(path: string, ...handlers: RequestHandler[]): Application;
27
28
/**
29
* Handle PUT requests to specified path
30
* @param {string} path - Route path pattern
31
* @param {...RequestHandler} handlers - Route handler functions
32
* @returns {Application} Application instance for chaining
33
*/
34
app.put(path: string, ...handlers: RequestHandler[]): Application;
35
36
/**
37
* Handle DELETE requests to specified path
38
* @param {string} path - Route path pattern
39
* @param {...RequestHandler} handlers - Route handler functions
40
* @returns {Application} Application instance for chaining
41
*/
42
app.delete(path: string, ...handlers: RequestHandler[]): Application;
43
44
/**
45
* Handle PATCH requests to specified path
46
* @param {string} path - Route path pattern
47
* @param {...RequestHandler} handlers - Route handler functions
48
* @returns {Application} Application instance for chaining
49
*/
50
app.patch(path: string, ...handlers: RequestHandler[]): Application;
51
52
/**
53
* Handle HEAD requests to specified path
54
* @param {string} path - Route path pattern
55
* @param {...RequestHandler} handlers - Route handler functions
56
* @returns {Application} Application instance for chaining
57
*/
58
app.head(path: string, ...handlers: RequestHandler[]): Application;
59
60
/**
61
* Handle OPTIONS requests to specified path
62
* @param {string} path - Route path pattern
63
* @param {...RequestHandler} handlers - Route handler functions
64
* @returns {Application} Application instance for chaining
65
*/
66
app.options(path: string, ...handlers: RequestHandler[]): Application;
67
68
/**
69
* Handle all HTTP methods for specified path
70
* @param {string} path - Route path pattern
71
* @param {...RequestHandler} handlers - Route handler functions
72
* @returns {Application} Application instance for chaining
73
*/
74
app.all(path: string, ...handlers: RequestHandler[]): Application;
75
```
76
77
**Usage Examples:**
78
79
```javascript
80
const app = express();
81
82
// Basic routes
83
app.get('/', (req, res) => {
84
res.send('Hello World!');
85
});
86
87
app.post('/users', (req, res) => {
88
res.json({ message: 'User created' });
89
});
90
91
// Multiple handlers
92
app.get('/protected', authenticate, authorize, (req, res) => {
93
res.json({ message: 'Protected resource' });
94
});
95
96
// Handle all methods
97
app.all('/api/*', cors, (req, res, next) => {
98
console.log(`${req.method} ${req.path}`);
99
next();
100
});
101
102
function authenticate(req, res, next) {
103
// Authentication logic
104
next();
105
}
106
107
function authorize(req, res, next) {
108
// Authorization logic
109
next();
110
}
111
```
112
113
### Route Parameters
114
115
Extract parameters from URL paths using route parameter patterns.
116
117
```javascript { .api }
118
/**
119
* Request handler function signature
120
* @param {Request} req - Express request object with params
121
* @param {Response} res - Express response object
122
* @param {NextFunction} next - Next middleware function
123
*/
124
type RequestHandler = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
125
```
126
127
**Route Parameter Patterns:**
128
129
- `:param` - Named parameter (matches any value except `/`)
130
- `:param?` - Optional parameter
131
- `:param*` - Wildcard parameter (matches including `/`)
132
- `:param+` - One or more parameter
133
- `*` - Wildcard (matches any path)
134
135
**Usage Examples:**
136
137
```javascript
138
// Named parameters
139
app.get('/users/:id', (req, res) => {
140
const userId = req.params.id;
141
res.json({ userId });
142
});
143
144
// Multiple parameters
145
app.get('/users/:userId/posts/:postId', (req, res) => {
146
const { userId, postId } = req.params;
147
res.json({ userId, postId });
148
});
149
150
// Optional parameters
151
app.get('/posts/:year/:month?', (req, res) => {
152
const { year, month } = req.params;
153
res.json({ year, month: month || 'all' });
154
});
155
156
// Wildcard routes
157
app.get('/files/*', (req, res) => {
158
const filePath = req.params[0]; // Everything after /files/
159
res.json({ filePath });
160
});
161
162
// Parameter with regex pattern
163
app.get('/users/:id(\\d+)', (req, res) => {
164
// Only matches numeric IDs
165
res.json({ id: req.params.id });
166
});
167
```
168
169
### Route Creation
170
171
Create route instances for method chaining and organization.
172
173
```javascript { .api }
174
/**
175
* Create route instance for path with chainable method handlers
176
* @param {string} path - Route path pattern
177
* @returns {Route} Route instance for chaining HTTP methods
178
*/
179
app.route(path: string): Route;
180
181
/**
182
* Route instance with chainable HTTP method handlers
183
*/
184
interface Route {
185
/** Route path pattern */
186
path: string;
187
/** HTTP methods handled by this route */
188
methods: { [method: string]: boolean };
189
190
/** Handle all HTTP methods */
191
all(...handlers: RequestHandler[]): Route;
192
/** Handle GET requests */
193
get(...handlers: RequestHandler[]): Route;
194
/** Handle POST requests */
195
post(...handlers: RequestHandler[]): Route;
196
/** Handle PUT requests */
197
put(...handlers: RequestHandler[]): Route;
198
/** Handle DELETE requests */
199
delete(...handlers: RequestHandler[]): Route;
200
/** Handle PATCH requests */
201
patch(...handlers: RequestHandler[]): Route;
202
/** Handle HEAD requests */
203
head(...handlers: RequestHandler[]): Route;
204
/** Handle OPTIONS requests */
205
options(...handlers: RequestHandler[]): Route;
206
}
207
```
208
209
**Usage Examples:**
210
211
```javascript
212
// Method chaining with route
213
app.route('/users/:id')
214
.get((req, res) => {
215
res.json({ message: 'Get user' });
216
})
217
.put((req, res) => {
218
res.json({ message: 'Update user' });
219
})
220
.delete((req, res) => {
221
res.json({ message: 'Delete user' });
222
});
223
224
// Common middleware for all methods
225
app.route('/api/posts/:id')
226
.all((req, res, next) => {
227
// Middleware for all methods
228
console.log(`Accessing post ${req.params.id}`);
229
next();
230
})
231
.get(getPost)
232
.put(updatePost)
233
.delete(deletePost);
234
```
235
236
### Parameter Middleware
237
238
Add middleware that runs when specific route parameters are encountered.
239
240
```javascript { .api }
241
/**
242
* Add callback triggers for route parameters
243
* @param {string} name - Parameter name
244
* @param {ParamHandler} handler - Parameter handler function
245
* @returns {Application} Application instance for chaining
246
*/
247
app.param(name: string, handler: ParamHandler): Application;
248
249
/**
250
* Parameter handler function signature
251
* @param {Request} req - Express request object
252
* @param {Response} res - Express response object
253
* @param {NextFunction} next - Next middleware function
254
* @param {any} value - Parameter value from URL
255
* @param {string} name - Parameter name
256
*/
257
type ParamHandler = (req: Request, res: Response, next: NextFunction, value: any, name: string) => void;
258
```
259
260
**Usage Examples:**
261
262
```javascript
263
// Parameter middleware for user ID
264
app.param('userId', (req, res, next, id) => {
265
// Load user and attach to request
266
User.findById(id, (err, user) => {
267
if (err) return next(err);
268
if (!user) return next(new Error('User not found'));
269
req.user = user;
270
next();
271
});
272
});
273
274
// Parameter middleware for validation
275
app.param('id', (req, res, next, id) => {
276
if (!/^\d+$/.test(id)) {
277
return next(new Error('ID must be numeric'));
278
}
279
next();
280
});
281
282
// Routes using the parameter
283
app.get('/users/:userId', (req, res) => {
284
// req.user is already loaded by param middleware
285
res.json(req.user);
286
});
287
288
app.get('/users/:userId/posts', (req, res) => {
289
// req.user is available here too
290
res.json({ user: req.user.id, posts: [] });
291
});
292
```
293
294
### Route Patterns
295
296
Advanced route pattern matching with regex and wildcards.
297
298
**Pattern Types:**
299
300
```javascript
301
// String patterns
302
app.get('/about', handler); // Exact match
303
app.get('/ab*cd', handler); // Wildcard
304
app.get('/ab+cd', handler); // One or more
305
app.get('/ab?cd', handler); // Optional character
306
307
// Regular expression patterns
308
app.get(/.*fly$/, handler); // Ends with 'fly'
309
app.get(/\/users\/(\d+)/, handler); // Numeric user ID
310
311
// Array of patterns
312
app.get(['/abcd', '/xyza'], handler); // Multiple exact matches
313
```
314
315
**Usage Examples:**
316
317
```javascript
318
// Wildcard patterns
319
app.get('/files/*', (req, res) => {
320
const file = req.params[0];
321
res.sendFile(path.join(__dirname, 'public', file));
322
});
323
324
// Regex patterns
325
app.get(/\/users\/(\d+)\/posts\/(\d+)/, (req, res) => {
326
const [userId, postId] = req.params;
327
res.json({ userId, postId });
328
});
329
330
// Complex patterns
331
app.get('/products/:category(electronics|books|clothing)', (req, res) => {
332
const category = req.params.category;
333
res.json({ category });
334
});
335
```
336
337
## Route Handler Types
338
339
```javascript { .api }
340
/**
341
* Next function for continuing middleware chain
342
* @param {Error} [error] - Optional error to pass to error handlers
343
*/
344
type NextFunction = (error?: Error) => void;
345
346
/**
347
* Error handling middleware signature
348
* @param {Error} err - Error object
349
* @param {Request} req - Express request object
350
* @param {Response} res - Express response object
351
* @param {NextFunction} next - Next middleware function
352
*/
353
type ErrorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => void;
354
```