- Spec files
npm-express
Describes: pkg:npm/express@4.21.x
- Description
- Fast, unopinionated, minimalist web framework for Node.js
- Author
- tessl
- Last updated
routing.md docs/
1# HTTP Routing23Route definition and HTTP method handling for creating RESTful APIs and web applications with pattern matching and parameter extraction.45## Capabilities67### HTTP Method Routing89Handle specific HTTP methods with route patterns and middleware functions.1011```javascript { .api }12/**13* Handle GET requests to specified path14* @param {string} path - Route path pattern15* @param {...RequestHandler} handlers - Route handler functions16* @returns {Application} Application instance for chaining17*/18app.get(path: string, ...handlers: RequestHandler[]): Application;1920/**21* Handle POST requests to specified path22* @param {string} path - Route path pattern23* @param {...RequestHandler} handlers - Route handler functions24* @returns {Application} Application instance for chaining25*/26app.post(path: string, ...handlers: RequestHandler[]): Application;2728/**29* Handle PUT requests to specified path30* @param {string} path - Route path pattern31* @param {...RequestHandler} handlers - Route handler functions32* @returns {Application} Application instance for chaining33*/34app.put(path: string, ...handlers: RequestHandler[]): Application;3536/**37* Handle DELETE requests to specified path38* @param {string} path - Route path pattern39* @param {...RequestHandler} handlers - Route handler functions40* @returns {Application} Application instance for chaining41*/42app.delete(path: string, ...handlers: RequestHandler[]): Application;4344/**45* Handle PATCH requests to specified path46* @param {string} path - Route path pattern47* @param {...RequestHandler} handlers - Route handler functions48* @returns {Application} Application instance for chaining49*/50app.patch(path: string, ...handlers: RequestHandler[]): Application;5152/**53* Handle HEAD requests to specified path54* @param {string} path - Route path pattern55* @param {...RequestHandler} handlers - Route handler functions56* @returns {Application} Application instance for chaining57*/58app.head(path: string, ...handlers: RequestHandler[]): Application;5960/**61* Handle OPTIONS requests to specified path62* @param {string} path - Route path pattern63* @param {...RequestHandler} handlers - Route handler functions64* @returns {Application} Application instance for chaining65*/66app.options(path: string, ...handlers: RequestHandler[]): Application;6768/**69* Handle all HTTP methods for specified path70* @param {string} path - Route path pattern71* @param {...RequestHandler} handlers - Route handler functions72* @returns {Application} Application instance for chaining73*/74app.all(path: string, ...handlers: RequestHandler[]): Application;75```7677**Usage Examples:**7879```javascript80const app = express();8182// Basic routes83app.get('/', (req, res) => {84res.send('Hello World!');85});8687app.post('/users', (req, res) => {88res.json({ message: 'User created' });89});9091// Multiple handlers92app.get('/protected', authenticate, authorize, (req, res) => {93res.json({ message: 'Protected resource' });94});9596// Handle all methods97app.all('/api/*', cors, (req, res, next) => {98console.log(`${req.method} ${req.path}`);99next();100});101102function authenticate(req, res, next) {103// Authentication logic104next();105}106107function authorize(req, res, next) {108// Authorization logic109next();110}111```112113### Route Parameters114115Extract parameters from URL paths using route parameter patterns.116117```javascript { .api }118/**119* Request handler function signature120* @param {Request} req - Express request object with params121* @param {Response} res - Express response object122* @param {NextFunction} next - Next middleware function123*/124type RequestHandler = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;125```126127**Route Parameter Patterns:**128129- `:param` - Named parameter (matches any value except `/`)130- `:param?` - Optional parameter131- `:param*` - Wildcard parameter (matches including `/`)132- `:param+` - One or more parameter133- `*` - Wildcard (matches any path)134135**Usage Examples:**136137```javascript138// Named parameters139app.get('/users/:id', (req, res) => {140const userId = req.params.id;141res.json({ userId });142});143144// Multiple parameters145app.get('/users/:userId/posts/:postId', (req, res) => {146const { userId, postId } = req.params;147res.json({ userId, postId });148});149150// Optional parameters151app.get('/posts/:year/:month?', (req, res) => {152const { year, month } = req.params;153res.json({ year, month: month || 'all' });154});155156// Wildcard routes157app.get('/files/*', (req, res) => {158const filePath = req.params[0]; // Everything after /files/159res.json({ filePath });160});161162// Parameter with regex pattern163app.get('/users/:id(\\d+)', (req, res) => {164// Only matches numeric IDs165res.json({ id: req.params.id });166});167```168169### Route Creation170171Create route instances for method chaining and organization.172173```javascript { .api }174/**175* Create route instance for path with chainable method handlers176* @param {string} path - Route path pattern177* @returns {Route} Route instance for chaining HTTP methods178*/179app.route(path: string): Route;180181/**182* Route instance with chainable HTTP method handlers183*/184interface Route {185/** Route path pattern */186path: string;187/** HTTP methods handled by this route */188methods: { [method: string]: boolean };189190/** Handle all HTTP methods */191all(...handlers: RequestHandler[]): Route;192/** Handle GET requests */193get(...handlers: RequestHandler[]): Route;194/** Handle POST requests */195post(...handlers: RequestHandler[]): Route;196/** Handle PUT requests */197put(...handlers: RequestHandler[]): Route;198/** Handle DELETE requests */199delete(...handlers: RequestHandler[]): Route;200/** Handle PATCH requests */201patch(...handlers: RequestHandler[]): Route;202/** Handle HEAD requests */203head(...handlers: RequestHandler[]): Route;204/** Handle OPTIONS requests */205options(...handlers: RequestHandler[]): Route;206}207```208209**Usage Examples:**210211```javascript212// Method chaining with route213app.route('/users/:id')214.get((req, res) => {215res.json({ message: 'Get user' });216})217.put((req, res) => {218res.json({ message: 'Update user' });219})220.delete((req, res) => {221res.json({ message: 'Delete user' });222});223224// Common middleware for all methods225app.route('/api/posts/:id')226.all((req, res, next) => {227// Middleware for all methods228console.log(`Accessing post ${req.params.id}`);229next();230})231.get(getPost)232.put(updatePost)233.delete(deletePost);234```235236### Parameter Middleware237238Add middleware that runs when specific route parameters are encountered.239240```javascript { .api }241/**242* Add callback triggers for route parameters243* @param {string} name - Parameter name244* @param {ParamHandler} handler - Parameter handler function245* @returns {Application} Application instance for chaining246*/247app.param(name: string, handler: ParamHandler): Application;248249/**250* Parameter handler function signature251* @param {Request} req - Express request object252* @param {Response} res - Express response object253* @param {NextFunction} next - Next middleware function254* @param {any} value - Parameter value from URL255* @param {string} name - Parameter name256*/257type ParamHandler = (req: Request, res: Response, next: NextFunction, value: any, name: string) => void;258```259260**Usage Examples:**261262```javascript263// Parameter middleware for user ID264app.param('userId', (req, res, next, id) => {265// Load user and attach to request266User.findById(id, (err, user) => {267if (err) return next(err);268if (!user) return next(new Error('User not found'));269req.user = user;270next();271});272});273274// Parameter middleware for validation275app.param('id', (req, res, next, id) => {276if (!/^\d+$/.test(id)) {277return next(new Error('ID must be numeric'));278}279next();280});281282// Routes using the parameter283app.get('/users/:userId', (req, res) => {284// req.user is already loaded by param middleware285res.json(req.user);286});287288app.get('/users/:userId/posts', (req, res) => {289// req.user is available here too290res.json({ user: req.user.id, posts: [] });291});292```293294### Route Patterns295296Advanced route pattern matching with regex and wildcards.297298**Pattern Types:**299300```javascript301// String patterns302app.get('/about', handler); // Exact match303app.get('/ab*cd', handler); // Wildcard304app.get('/ab+cd', handler); // One or more305app.get('/ab?cd', handler); // Optional character306307// Regular expression patterns308app.get(/.*fly$/, handler); // Ends with 'fly'309app.get(/\/users\/(\d+)/, handler); // Numeric user ID310311// Array of patterns312app.get(['/abcd', '/xyza'], handler); // Multiple exact matches313```314315**Usage Examples:**316317```javascript318// Wildcard patterns319app.get('/files/*', (req, res) => {320const file = req.params[0];321res.sendFile(path.join(__dirname, 'public', file));322});323324// Regex patterns325app.get(/\/users\/(\d+)\/posts\/(\d+)/, (req, res) => {326const [userId, postId] = req.params;327res.json({ userId, postId });328});329330// Complex patterns331app.get('/products/:category(electronics|books|clothing)', (req, res) => {332const category = req.params.category;333res.json({ category });334});335```336337## Route Handler Types338339```javascript { .api }340/**341* Next function for continuing middleware chain342* @param {Error} [error] - Optional error to pass to error handlers343*/344type NextFunction = (error?: Error) => void;345346/**347* Error handling middleware signature348* @param {Error} err - Error object349* @param {Request} req - Express request object350* @param {Response} res - Express response object351* @param {NextFunction} next - Next middleware function352*/353type ErrorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => void;354```