### Basic Router Setup and Routes Source: https://github.com/expressjs/express/blob/master/_autodocs/9-router.md Example of setting up a basic router with GET and POST routes for a root path and user creation. ```javascript const express = require('express'); const router = express.Router(); router.get('/', (req, res) => { res.json({ message: 'API root' }); }); router.post('/users', (req, res) => { res.json({ created: true }); }); module.exports = router; ``` -------------------------------- ### Create a basic Express server with routing Source: https://github.com/expressjs/express/blob/master/Readme.md Minimal Express application that imports the framework, creates an app instance, defines a GET route, and starts listening on port 3000. Use this as a starting point for any Express project. ```javascript import express from 'express' const app = express() app.get('/', (req, res) => { res.send('Hello World') }) app.listen(3000, () => { console.log('Server is running on http://localhost:3000') }) ``` -------------------------------- ### Basic Express Server Setup Source: https://github.com/expressjs/express/blob/master/_autodocs/10-quick-reference.md Sets up a basic Express.js server with JSON parsing and static file serving. This is a foundational example for most Express applications. ```javascript const express = require('express'); const app = express(); app.use(express.json()); app.use(express.static('public')); app.get('/', (req, res) => { res.send('Hello World'); }); app.listen(3000, () => { console.log('Server running on port 3000'); }); ``` -------------------------------- ### Start an HTTP Server Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md The `app.listen` method starts an HTTP server on a specified port and host. It returns a Node.js `http.Server` instance and can optionally accept a callback to execute once the server begins listening. ```javascript app.listen(port?: number, hostname?: string, backlog?: number, callback?: Function): http.Server ``` ```javascript const app = express(); app.listen(3000, () => { console.log('Server listening on port 3000'); }); ``` ```javascript app.listen(8080, 'localhost', () => { console.log('Server listening on localhost:8080'); }); ``` -------------------------------- ### Create and Run Express App Source: https://github.com/expressjs/express/blob/master/_autodocs/10-quick-reference.md Use this to create an Express application instance and start listening for incoming connections on a specified port. The `http.createServer` method is an alternative way to start the server. ```javascript const express = require('express'); const app = express(); app.listen(port, [hostname], [callback]) http.createServer(app).listen(port) ``` -------------------------------- ### Clone Express repository and run examples Source: https://github.com/expressjs/express/blob/master/Readme.md Clone the Express repository with minimal history and run example applications to explore framework capabilities. ```bash git clone https://github.com/expressjs/express.git --depth 1 && cd express ``` ```bash npm install ``` ```bash node examples/content-negotiation ``` -------------------------------- ### Express View Rendering Setup Source: https://github.com/expressjs/express/blob/master/_autodocs/10-quick-reference.md Configures Express to use a view engine (EJS in this example) and specifies the directory for view templates. Used for server-side rendering of HTML. ```javascript app.set('view engine', 'ejs'); app.set('views', './views'); app.get('/', (req, res) => { res.render('index', { title: 'Home', user: req.user }); }); ``` -------------------------------- ### Generate and run an Express application Source: https://github.com/expressjs/express/blob/master/Readme.md Use the express-generator to create a new application scaffold, then install dependencies and start the development server. ```bash express /tmp/foo && cd /tmp/foo ``` ```bash npm install ``` ```bash npm start ``` -------------------------------- ### Application Creation and Listening Source: https://github.com/expressjs/express/blob/master/_autodocs/10-quick-reference.md Methods for creating an Express application instance and starting an HTTP server. ```APIDOC ## Application Creation and Listening ### Description Methods for creating an Express application instance and starting an HTTP server. ### Methods - `express()`: Creates an Express application instance. - `app.listen(port, [hostname], [callback])`: Starts an HTTP server and listens for connections on the specified port. - `http.createServer(app).listen(port)`: Creates an HTTP server using the Express app. ### Parameters #### `app.listen` Parameters - **port** (number) - Required - The port to listen on. - **hostname** (string) - Optional - The hostname to listen on. - **callback** (function) - Optional - A callback function to execute when the server has been started. #### `http.createServer` Parameters - **app** (object) - Required - The Express application instance. - **port** (number) - Required - The port to listen on. ``` -------------------------------- ### Nested Routers Example Source: https://github.com/expressjs/express/blob/master/_autodocs/9-router.md Demonstrates how to create and mount sub-routers within a main router to build deeply nested route hierarchies. ```javascript const express = require('express'); const app = express(); // Create main router const v1Router = express.Router(); // Create sub-routers const usersRouter = express.Router(); const postsRouter = express.Router(); // Define user routes usersRouter.get('/', (req, res) => { res.json({ resource: 'users' }); }); // Define post routes postsRouter.get('/', (req, res) => { res.json({ resource: 'posts' }); }); // Mount sub-routers on main router v1Router.use('/users', usersRouter); v1Router.use('/posts', postsRouter); // Mount main router on app app.use('/api/v1', v1Router); // Routes: // GET /api/v1/users // GET /api/v1/posts ``` -------------------------------- ### Complete Routing Example with Nested Routers Source: https://github.com/expressjs/express/blob/master/_autodocs/9-router.md Sets up a multi-file routing structure for API version 1, including authentication and user routes, and mounts them under a base path. ```javascript // routes/api/v1/auth.js const express = require('express'); const router = express.Router(); router.post('/login', (req, res) => { const { username, password } = req.body; // authenticate user res.json({ token: 'jwt-token' }); }); router.post('/logout', (req, res) => { // logout user res.json({ success: true }); }); module.exports = router; // routes/api/v1/users.js const express = require('express'); const router = express.Router(); router.param('userId', (req, res, next, userId) => { // Load user next(); }); router.get('/', (req, res) => { res.json([]); }); router.get('/:userId', (req, res) => { res.json(req.user); }); module.exports = router; // routes/api/v1/index.js const express = require('express'); const router = express.Router(); const authRouter = require('./auth'); const usersRouter = require('./users'); router.use('/auth', authRouter); router.use('/users', usersRouter); module.exports = router; // app.js const express = require('express'); const apiV1 = require('./routes/api/v1'); const app = express(); app.use(express.json()); app.use('/api/v1', apiV1); // Routes available: // POST /api/v1/auth/login // POST /api/v1/auth/logout // GET /api/v1/users // GET /api/v1/users/123 app.listen(3000); ``` -------------------------------- ### View Constructor Example Source: https://github.com/expressjs/express/blob/master/_autodocs/4-view.md Instantiates a new View object with specified options, including default engine, engines cache, and root directory. ```javascript const View = require('express/lib/view'); const view = new View('user', { defaultEngine: 'ejs', engines: {}, root: '/path/to/views' }); ``` -------------------------------- ### Run Express test suite Source: https://github.com/expressjs/express/blob/master/Readme.md Install dependencies and execute the complete test suite to verify Express functionality and integrity. ```bash npm install ``` ```bash npm test ``` -------------------------------- ### Express application listen method with HTTP server wrapper Source: https://github.com/expressjs/express/wiki/Migrating-from-2.x-to-3.x Shows two equivalent approaches for starting an Express application: using the convenience app.listen() method or manually wrapping the app with http.createServer(). The app.listen() method is a shorthand that internally creates an HTTP server. ```javascript var app = express(); app.listen(3000); ``` ```javascript var app = express() , http = require('http'); http.createServer(app).listen(3000); ``` -------------------------------- ### Set and Get Application Settings Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Configure application settings like view engines or directories. Use `app.set()` to assign a value and `app.get()` to retrieve it. ```javascript app.set('view engine', 'ejs'); app.set('views', '/path/to/views'); const viewEngine = app.set('view engine'); ``` -------------------------------- ### app.listen Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Starts an HTTP server on the specified port and host, making the application accessible. It returns a Node.js http.Server instance and can optionally execute a callback once the server is listening. ```APIDOC ## app.listen([port], [host], [backlog], [callback]) ### Description Create and start an HTTP server listening on the specified port and host. ### Method `app.listen ### Parameters #### Path Parameters - **port** (number) - No - The port to listen on (0 = any available port) - **hostname** (string) - No - The host address to bind to - **backlog** (number) - No - Maximum length of pending connections queue - **callback** (Function) - No - Invoked when the server starts listening ### Returns A Node.js `http.Server` instance. ### Example ```javascript const app = express(); app.listen(3000, () => { console.log('Server listening on port 3000'); }); app.listen(8080, 'localhost', () => { console.log('Server listening on localhost:8080'); }); ``` ``` -------------------------------- ### Basic res.render() Example Source: https://github.com/expressjs/express/blob/master/_autodocs/3-response.md Renders a template view named 'index' and passes a 'title' option to it. ```javascript res.render('index', { title: 'Home' }); ``` -------------------------------- ### Map custom template engine to file extension using app.engine() Source: https://github.com/expressjs/express/wiki/Migrating-from-2.x-to-3.x Demonstrates how to use app.engine() to map a custom rendering function to a file extension. This example shows integrating a markdown library to render .md files by reading the file, parsing it with the markdown library, and invoking the callback with the rendered output. ```javascript var markdown = require('some-markdown-library'); app.engine('md', function(path, options, fn){ fs.readFile(path, 'utf8', function(err, str){ if (err) return fn(err); str = markdown.parse(str).toString(); fn(null, str); }); }); ``` -------------------------------- ### Express Static File Serving Source: https://github.com/expressjs/express/blob/master/_autodocs/10-quick-reference.md Shows how to serve static files (like HTML, CSS, JS) from a directory using `express.static`. Includes examples with options and serving from multiple directories. ```javascript // Serve from public directory app.use(express.static('public')); // With options app.use(express.static('public', { maxAge: '1d', etag: false })); // Multiple directories app.use(express.static('public')); app.use(express.static('uploads')); ``` -------------------------------- ### Install Express generator globally Source: https://github.com/expressjs/express/blob/master/Readme.md Install the Express application generator tool globally to quickly scaffold new Express projects. The generator version matches the Express major version. ```bash npm install -g express-generator@4 ``` -------------------------------- ### Install Express package via npm Source: https://github.com/expressjs/express/blob/master/Readme.md Standard npm command to install Express as a project dependency. Requires Node.js 18 or higher and an existing package.json file. ```bash npm install express ``` -------------------------------- ### Express Application Setup with Locals and Rendering Source: https://github.com/expressjs/express/wiki/New-features-in-3.x Configure Express application with local variables and template engine mapping. The app.locals object stores application-level variables accessible in views, while app.engine() maps file extensions to template engines. app.render() enables server-side view rendering with optional parameters. ```JavaScript const express = require('express'); const app = express(); // Set application locals app.locals.foo = 'bar'; app.locals({ foo: 'bar', bar: 'baz' }); // Map template engine app.engine('html', require('ejs').renderFile); // Render app-level views app.render('index', { title: 'Home' }, (err, html) => { if (err) console.error(err); console.log(html); }); ``` -------------------------------- ### Enable Production Optimizations Source: https://github.com/expressjs/express/blob/master/_autodocs/10-quick-reference.md Conditionally enable production-specific optimizations based on the 'env' setting. This example enables view caching in production. ```javascript if (app.get('env') === 'production') { app.enable('view cache'); } ``` -------------------------------- ### Example: Validate User ID Parameter Source: https://github.com/expressjs/express/blob/master/_autodocs/6-utilities.md Demonstrates how to use `app.param()` to validate a 'userId' parameter, ensuring it's a number and looking up the corresponding user before proceeding. ```javascript // Validate user IDs app.param('userId', (req, res, next, userId) => { if (!/^\d+$/.test(userId)) { return res.status(400).send('Invalid user ID'); } // Look up user User.findById(userId, (err, user) => { if (err) return next(err); if (!user) return res.status(404).send('User not found'); req.user = user; next(); }); }); app.get('/users/:userId', (req, res) => { res.json(req.user); }); ``` -------------------------------- ### Application Configuration Source: https://github.com/expressjs/express/blob/master/_autodocs/10-quick-reference.md Methods for setting and getting application settings, and enabling/disabling features. ```APIDOC ## Application Configuration ### Description Methods for setting and getting application settings, and enabling/disabling features. ### Methods - `app.set(setting, value)`: Sets a configuration setting. - `app.get(setting)`: Retrieves the value of a configuration setting. - `app.enable(setting)`: Enables a setting (sets it to true). - `app.disable(setting)`: Disables a setting (sets it to false). - `app.enabled(setting)`: Checks if a setting is enabled (true). - `app.disabled(setting)`: Checks if a setting is disabled (false). ### Parameters #### `app.set` Parameters - **setting** (string) - Required - The name of the setting. - **value** (any) - Required - The value to set for the setting. #### `app.get` Parameters - **setting** (string) - Required - The name of the setting to retrieve. #### `app.enable`/`app.disable`/`app.enabled`/`app.disabled` Parameters - **setting** (string) - Required - The name of the setting to enable, disable, or check. ``` -------------------------------- ### Middleware Execution Order Example Source: https://github.com/expressjs/express/blob/master/_autodocs/8-middleware-flow.md Demonstrates the order of middleware execution in an Express application, including global middleware, path-specific middleware, and route handlers. Ensure middleware is registered in the desired execution sequence. ```javascript const express = require('express'); const app = express(); console.log('1. Application startup'); // Registered first app.use((req, res, next) => { console.log('3. Global middleware'); next(); }); // Registered second app.use('/api', (req, res, next) => { console.log('4. API middleware'); next(); }); // Route handler app.get('/api/users', (req, res) => { console.log('5. Route handler'); res.send('Users'); }); // Error handler app.use((err, req, res, next) => { console.log('Error:', err.message); res.status(500).send('Error'); }); console.log('2. Routes registered'); app.listen(3000, () => { console.log('Server started'); }); // When request arrives: GET /api/users // Output: // 1. Application startup // 2. Routes registered // Server started // 3. Global middleware // 4. API middleware // 5. Route handler ``` -------------------------------- ### Retrieve Application Setting Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Get the value of a specific application setting. This is useful for checking current configurations. ```javascript const env = app.get('env'); const views = app.get('views'); ``` -------------------------------- ### Get Full Application Path Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Determine the complete path of an application by tracing its mounting hierarchy from the root. This is useful for nested applications. ```javascript const parent = express(); const admin = express(); const dashboard = express(); parent.use('/admin', admin); admin.use('/dashboard', dashboard); console.log(dashboard.path()); // '/admin/dashboard' ``` -------------------------------- ### Route Matching Precedence Example Source: https://github.com/expressjs/express/blob/master/_autodocs/8-middleware-flow.md Demonstrates the order of route matching in Express. Exact string matches take precedence over parameterized, wildcard, and regex routes. ```javascript app.get('/users', handler1); // Matches: /users app.get('/users/:id', handler2); // Matches: /users/123, /users/abc app.get('/users/*', handler3); // Matches: /users/123/profile app.get(/.*/, handler4); // Matches: anything // GET /users → handler1 // GET /users/123 → handler2 // GET /users/123/posts → handler3 // GET /anything-else → handler4 ``` -------------------------------- ### Express Middleware Examples Source: https://github.com/expressjs/express/blob/master/_autodocs/10-quick-reference.md Illustrates different ways to implement middleware in Express: global, path-specific, and multiple middleware functions on a single route. Middleware intercepts requests before they reach the route handler. ```javascript // Global middleware app.use((req, res, next) => { console.log(`${req.method} ${req.path}`); next(); }); // Path-specific middleware app.use('/api', (req, res, next) => { res.header('X-API-Version', '1.0'); next(); }); // Multiple middleware on route app.post('/users', validateBody, checkAuth, (req, res) => { res.json({ created: true }); }); ``` -------------------------------- ### Using `app.use` with route parameters in Express 4.x Source: https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x Express 4.x enhances `app.use` to accept route parameters, allowing middleware to be scoped to specific URL patterns. This example demonstrates how to define a middleware function with a parameterized path and access `req.params` within it. ```javascript app.use('/users/:user_id', function(req, res, next) { // req.params.user_id exists here }); ``` -------------------------------- ### Defining Express.js Error Handling Middleware (JavaScript) Source: https://github.com/expressjs/express/wiki/Migrating-from-2.x-to-3.x This example illustrates the correct way to define an error-handling middleware in Express.js. It shows how to chain regular middleware (like `bodyParser`, `cookieParser`, `session`, `router`) and then place a 4-argument error-handling middleware at the end of the chain to catch errors passed via `next(err)`. This allows for centralized error response handling within an Express application. ```js app.use(express.bodyParser()) app.use(express.cookieParser()) app.use(express.session()) app.use(app.router) // the router itself (app.get(), app.put() etc) app.use(function(err, req, res, next){ // if an error occurs Connect will pass it down // through these "error-handling" middleware // allowing you to respond however you like res.send(500, { error: 'Sorry something bad happened!' }); }) ``` -------------------------------- ### app.all() Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Attach handlers for all HTTP methods on a path. ```APIDOC ## app.all(path, handler, [handler, ...]) ### Description Attach handlers for all HTTP methods on a path. ### Method Signature `app.all(path: string, handler: Function, ...handlers: Function[]): this` ### Parameters #### Path Parameter - **path** (string) - Required - The path pattern for the route. - **handler** (Function(req, res, next)) - Required - Middleware function(s). - **handlers** (Function) - Optional - Additional middleware functions. ### Returns The application instance for chaining. ### Example ```javascript app.all('/api/*', (req, res, next) => { console.log('API request received'); next(); }); app.all('/admin', requireAuth, (req, res) => { res.send('Admin dashboard'); }); ``` ``` -------------------------------- ### Install ESON Package via NPM Source: https://github.com/expressjs/express/wiki/ESON-JSON-Configuration Install the Extended-JSON (ESON) library as a project dependency. This library enables JSON transformation through plugins for flexible application configuration management. ```bash npm install eson --save ``` -------------------------------- ### Configuration Source: https://github.com/expressjs/express/blob/master/_autodocs/README.md Explains how to configure Express application settings, including using `app.set()`, `app.get()`, and boolean settings with `app.enable()` and `app.disable()`. ```APIDOC ## Configuration ### Description This section details how to configure settings within an Express application. It covers retrieving and setting arbitrary application settings using `app.set()` and `app.get()`, as well as managing boolean settings with `app.enable()` and `app.disable()`. It also notes the influence of the `NODE_ENV` environment variable on default behaviors. ### Application Settings - `app.set(setting, value)`: Sets the `setting` to `value`. - `app.get(setting)`: Returns the value of the `setting`. - `app.enable(setting)`: Enables a setting (sets it to `true`). - `app.disable(setting)`: Disables a setting (sets it to `false`). ### Environment Variables - `NODE_ENV`: This environment variable can affect default configurations and behaviors in Express and its middleware. ``` -------------------------------- ### view.ext Source: https://github.com/expressjs/express/blob/master/_autodocs/4-view.md Get the file extension of the template, including the leading dot. ```APIDOC ## view.ext ### Description Gets the file extension of the template (with leading dot). ### Type String ### Behavior - Extracted from the filename if present - Added from `defaultEngine` if filename has no extension - Always includes the leading dot ### Example ```javascript const view = new View('index.ejs', { /* ... */ }); console.log(view.ext); // '.ejs' const view = new View('index', { defaultEngine: 'hbs', /* ... */ }); console.log(view.ext); // '.hbs' ``` ``` -------------------------------- ### Using Express.js Utilities and Middleware Source: https://github.com/expressjs/express/blob/master/_autodocs/6-utilities.md Demonstrates how to import and utilize built-in middleware like express.json() and express.static(), create custom routers using express.Router(), and access prototype objects for application, request, and response. ```javascript const express = require('express'); const { Router, Route, application, request, response } = express; // Use built-in middleware const app = express(); app.use(express.json()); app.use(express.static('public')); // Create custom router const router = new Router(); router.get('/', (req, res) => { res.send('OK'); }); // Access prototypes console.log(application === express.application); // true console.log(request === express.request); // true console.log(response === express.response); // true ``` -------------------------------- ### Express HTTP HEAD Method Support Source: https://github.com/expressjs/express/wiki/New-features-in-3.x Handle HTTP HEAD requests using app.head() method. HEAD requests are identical to GET requests except the server must not return a message body, only headers. Express automatically handles HEAD requests for GET routes, but explicit app.head() allows custom HEAD-specific logic. ```JavaScript app.get('/resource', (req, res) => { res.set('Content-Length', 1234); res.set('Content-Type', 'application/json'); res.json({ data: 'value' }); }); // Explicit HEAD handler app.head('/resource', (req, res) => { res.set('Content-Length', 1234); res.set('Content-Type', 'application/json'); res.end(); }); ``` -------------------------------- ### Create a Router Instance Source: https://github.com/expressjs/express/blob/master/_autodocs/9-router.md Instantiate a new router object. Options can be provided to configure case sensitivity, strict trailing slash matching, and parameter merging. ```javascript const router = express.Router(options); ``` -------------------------------- ### Get Request Path Source: https://github.com/expressjs/express/blob/master/_autodocs/2-request.md Access the path portion of the URL, excluding any query string, using `req.path`. ```javascript // URL: /search?q=test req.path; // '/search' ``` -------------------------------- ### Configuring a Template Engine Correctly Source: https://github.com/expressjs/express/blob/master/_autodocs/7-errors.md Shows the correct way to set up a view engine like EJS in Express.js to avoid 'missing template engine' errors. ```javascript const ejs = require('ejs'); const app = express(); app.set('view engine', 'ejs'); app.set('views', './views'); app.get('/', (req, res) => { res.render('index', { title: 'Home' }); }); ``` -------------------------------- ### Express.js Request Properties Source: https://github.com/expressjs/express/blob/master/_autodocs/10-quick-reference.md Access common properties of the request object to get information about the incoming HTTP request. ```javascript req.method // HTTP method req.path // URL path req.query // Query string parameters req.params // Route parameters req.body // Parsed body (requires middleware) req.headers // Request headers object req.ip // Client IP address req.secure // Boolean, true if HTTPS req.xhr // Boolean, true if XMLHttpRequest req.app // Reference to app ``` -------------------------------- ### Setting Application and Request Locals Source: https://github.com/expressjs/express/blob/master/_autodocs/8-middleware-flow.md Demonstrates how to set application-level locals using `app.locals` and request-level locals using `res.locals`. Request-level locals override application-level ones. ```javascript const app = express(); // Application-level locals app.locals.title = 'My Application'; app.locals.company = 'ACME Corp'; app.get('/page', (req, res) => { // Request-level locals (overrides app.locals) res.locals.user = req.user; res.locals.title = 'Page Title'; // overrides app.locals.title // All locals available in view res.render('page'); // View can access: title, company, user }); ``` -------------------------------- ### Router Constructor Source: https://github.com/expressjs/express/blob/master/_autodocs/9-router.md Creates a new router instance. Options can be provided to configure the router's behavior, such as case sensitivity, strict trailing slash handling, and parameter merging. ```APIDOC ## express.Router([options]) Create a new router instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Options - **options** (object) - Optional - Router configuration options - **caseSensitive** (boolean) - Optional - Default: `false` - Treat routes as case-sensitive - **strict** (boolean) - Optional - Default: `false` - Require trailing slashes in routes - **mergeParams** (boolean) - Optional - Default: `false` - Preserve parent router's params ### Returns A router instance with routing methods attached. ### Example ```javascript const express = require('express'); const router = express.Router(); router.get('/', (req, res) => { res.json({ message: 'API root' }); }); router.post('/users', (req, res) => { res.json({ created: true }); }); module.exports = router; ``` ``` -------------------------------- ### Handle All HTTP Methods with app.all() Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Attach handlers that will be executed for all HTTP methods on a given path. Useful for common logic like authentication or logging for a group of routes. ```javascript app.all('/api/*', (req, res, next) => { console.log('API request received'); next(); }); app.all('/admin', requireAuth, (req, res) => { res.send('Admin dashboard'); }); ``` -------------------------------- ### app.use() Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Mount middleware or sub-applications at a specified path. Middleware and routes mounted with app.use() will handle all HTTP methods. ```APIDOC ## app.use([path], handler, [handler, ...]) ### Description Mount middleware or sub-applications at a specified path. Middleware and routes mounted with `app.use()` will handle all HTTP methods. ### Method Signature `app.use(path?: string | RegExp | Function[], handler: Function | Express.Application, ...handlers: Function[]): this` ### Parameters #### Path Parameter - **path** (string, RegExp, or function) - Optional - The path to mount the middleware or application at. Defaults to '/'. - **handler** (Function or Express Application) - Required - Middleware function(s) or another Express app to mount. - **handlers** (Function) - Optional - Additional middleware functions. ### Returns The application instance for chaining. ### Behavior - If `path` is omitted, defaults to `/`. - Flattens arrays of middleware. - When an Express app is mounted, its `mountpath` property is set and it inherits parent app settings. - Middleware is executed for any HTTP method. ### Example ```javascript // Mount middleware at root app.use(express.json()); app.use(express.static('public')); // Mount middleware at a specific path app.use('/admin', requireAuth, adminRouter); // Mount a sub-application const api = express(); api.get('/users', (req, res) => { /* ... */ }); app.use('/api', api); // Mount multiple middleware app.use('/api', validateApiKey, apiRouter, errorHandler); ``` ``` -------------------------------- ### Full Template Rendering Flow with EJS Source: https://github.com/expressjs/express/blob/master/_autodocs/4-view.md Demonstrates setting up the EJS template engine and rendering views both programmatically and using `res.render`. Use this for complex rendering logic or when sending rendered HTML in non-HTTP contexts. ```javascript const express = require('express'); const app = express(); // Set up template engine app.set('view engine', 'ejs'); app.set('views', '/path/to/views'); // Create and render a view programmatically app.get('/email', (req, res, next) => { app.render('email', { to: 'user@example.com', subject: 'Welcome' }, (err, html) => { if (err) return next(err); // Send email with html sendEmail(html); res.send('Email sent'); }); }); // Using res.render (simpler approach) app.get('/profile', (req, res) => { res.render('profile', { user: req.user, title: 'User Profile' }); }); ``` -------------------------------- ### Using Built-in Express Middleware and Exports Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Demonstrates how to use Express's built-in middleware for parsing JSON and serving static files, and how to import Router and Route constructors. ```javascript const express = require('express'); const app = express(); // Use built-in middleware app.use(express.json()); app.use(express.static('public')); // Or import directly const { Router, Route } = express; ``` -------------------------------- ### Get Application Mount Path Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Retrieve the path pattern at which a sub-application is mounted within the main application. Useful for understanding routing context. ```javascript const app = express(); const api = express(); api.get('/users', (req, res) => { console.log(api.mountpath); // '/api' }); app.use('/api', api); ``` -------------------------------- ### Get Request Subdomains Source: https://github.com/expressjs/express/blob/master/_autodocs/2-request.md Retrieve an array of subdomains from the hostname using `req.subdomains`. The result is influenced by the 'subdomain offset' setting, which determines the main domain. ```javascript // Hostname: foo.bar.example.com (subdomain offset = 2) req.subdomains; // ['bar', 'foo'] ``` ```javascript // Hostname: foo.bar.example.com (subdomain offset = 3) req.subdomains; // ['foo'] ``` -------------------------------- ### Create Route Instance with app.route() Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Create a new Route instance for the given path. Routes are isolated middleware stacks for specific paths, allowing chaining of HTTP method handlers. ```javascript app.route('/users/:id') .get((req, res) => { /* get user */ }) .put((req, res) => { /* update user */ }) .delete((req, res) => { /* delete user */ }); ``` -------------------------------- ### Create an Express Application Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Instantiate a new Express application. This function returns an object with methods for routing, middleware, and configuration. ```javascript const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World'); }); app.listen(3000); ``` -------------------------------- ### Mount Middleware with app.use() Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Mount middleware or sub-applications at a specified path. Middleware and routes mounted with app.use() will handle all HTTP methods. Arrays of middleware are flattened. ```javascript app.use(express.json()); app.use(express.static('public')); // Mount middleware at a specific path app.use('/admin', requireAuth, adminRouter); // Mount a sub-application const api = express(); api.get('/users', (req, res) => { /* ... */ }); app.use('/api', api); // Mount multiple middleware app.use('/api', validateApiKey, apiRouter, errorHandler); ``` -------------------------------- ### app.route() Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Create a new Route instance for the given path. Routes are isolated middleware stacks for specific paths. ```APIDOC ## app.route(path) ### Description Create a new Route instance for the given path. Routes are isolated middleware stacks for specific paths. ### Method Signature `app.route(path: string): Route` ### Parameters #### Path Parameter - **path** (string) - Required - The path to create the route for. ### Returns A `Route` object (from the `router` package) with HTTP method handlers attached. ### Example ```javascript app.route('/users/:id') .get((req, res) => { /* get user */ }) .put((req, res) => { /* update user */ }) .delete((req, res) => { /* delete user */ }); ``` ``` -------------------------------- ### Path-Based Middleware Registration Source: https://github.com/expressjs/express/blob/master/_autodocs/8-middleware-flow.md Mount middleware at specific paths to control execution scope. Middleware registered at a path like '/api' will only run for requests starting with that path. ```javascript app.use((req, res, next) => { console.log('Global middleware'); next(); }); app.use('/api', (req, res, next) => { console.log('API middleware'); next(); }); app.use('/admin', requireAuth, adminRouter); // Request to /api/users // Logs: "Global middleware", "API middleware", then route handler ``` -------------------------------- ### req.fresh Source: https://github.com/expressjs/express/blob/master/_autodocs/2-request.md Checks if the request is fresh, meaning the client's cache is still valid based on ETag or Last-Modified headers. This property is primarily for GET and HEAD requests. ```APIDOC ## req.fresh ### Description Checks if the request is fresh (client cache is valid). ### Type Boolean ### Behavior - Returns `true` if the resource has not been modified (based on `ETag` or `Last-Modified`) - Only applies to GET and HEAD requests - Uses the response `ETag` and `Last-Modified` headers - Returns `false` for other methods or if no caching headers ### Example ```javascript if (req.fresh) { res.status(304).end(); // Not Modified } ``` ``` -------------------------------- ### Handle All HTTP Methods with router.all() Source: https://github.com/expressjs/express/blob/master/_autodocs/9-router.md Use `router.all()` to attach handlers that will be executed for any HTTP method on a specified path. Useful for common logic like authentication. ```javascript const router = express.Router(); router.all('/protected', authenticate, (req, res, next) => { console.log('All methods on /protected require auth'); next(); }); router.get('/protected', (req, res) => { res.send('GET protected resource'); }); router.post('/protected', (req, res) => { res.send('POST protected resource'); }); ``` -------------------------------- ### Get Response Header Value Source: https://github.com/expressjs/express/blob/master/_autodocs/3-response.md Use `res.get()` to retrieve the value of a specific response header. It returns the header's value as a string or `undefined` if the header is not set. ```javascript const contentType = res.get('Content-Type'); const etag = res.get('ETag'); ``` -------------------------------- ### Enable Application Setting Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Enable a specific application setting by setting its value to `true`. This method supports chaining. ```javascript app.enable('x-powered-by'); app.enable('view cache'); ``` -------------------------------- ### Express JSON API Endpoints Source: https://github.com/expressjs/express/blob/master/_autodocs/10-quick-reference.md Demonstrates how to create basic JSON API endpoints for retrieving and creating user data. Handles GET and POST requests for '/api/users'. ```javascript app.get('/api/users', (req, res) => { res.json([{ id: 1, name: 'John' }]); }); app.post('/api/users', (req, res) => { const user = req.body; res.status(201).json(user); }); app.get('/api/users/:id', (req, res) => { const { id } = req.params; res.json({ id, name: 'John' }); }); ``` -------------------------------- ### Get Trusted Proxy IP Addresses Source: https://github.com/expressjs/express/blob/master/_autodocs/2-request.md When 'trust proxy' is enabled, `req.ips` returns an array of trusted proxy addresses and the client address from the `X-Forwarded-For` header, in reverse order. ```javascript // X-Forwarded-For: client, proxy1, proxy2 req.ips; // ['proxy2', 'proxy1', 'client'] ``` -------------------------------- ### Multiple and Combined Route Parameter Handlers Source: https://github.com/expressjs/express/blob/master/_autodocs/8-middleware-flow.md Demonstrates registering multiple handlers for the same parameter or a single handler for multiple parameters. Handlers execute in the order they are registered. ```javascript // Both handlers execute in order app.param('userId', validateUserId); app.param('userId', loadUserData); // Single handler for multiple params app.param(['userId', 'adminId'], validateId) ``` -------------------------------- ### Router: Add `Router.all()` Method Source: https://github.com/expressjs/express/blob/master/History.md Introduced the `Router.all()` method for handling all HTTP methods. ```javascript router: add Router.all() method ``` -------------------------------- ### Handle Specific HTTP Methods Source: https://github.com/expressjs/express/blob/master/_autodocs/1-application.md Attach a handler for a specific HTTP method (GET, POST, PUT, DELETE, etc.) to a path. Multiple handlers can be chained for a single route. ```javascript app.get('/', (req, res) => { res.send('GET request'); }); app.post('/users', (req, res) => { res.json({ id: 1, created: true }); }); app.get('/users/:id', (req, res) => { const userId = req.params.id; res.send(`User ${userId}`); }); // Chain multiple handlers app.post('/articles', validateArticle, saveArticle, (req, res) => { res.status(201).json(req.article); }); ``` -------------------------------- ### Route Chaining for Multiple HTTP Methods Source: https://github.com/expressjs/express/blob/master/_autodocs/8-middleware-flow.md Use route chaining to define multiple HTTP methods (GET, PUT, DELETE) for the same URL path, improving code organization. ```javascript app.route('/users/:id') .get((req, res) => { res.send('Get user'); }) .put((req, res) => { res.send('Update user'); }) .delete((req, res) => { res.send('Delete user'); }); ``` -------------------------------- ### Adding `app.purge` and `router.purge` Source: https://github.com/expressjs/express/blob/master/History.md Support for the PURGE HTTP method has been added via `app.purge`, `router.purge`, and inclusion in `app.all`. ```javascript app.purge() router.purge() app.all() // Include PURGE method ``` -------------------------------- ### Define HTTP Method Handlers Source: https://github.com/expressjs/express/blob/master/_autodocs/9-router.md Attach handlers for specific HTTP methods like GET, POST, PUT, and DELETE to defined routes. Supports chaining multiple handlers. ```javascript const router = express.Router(); router.get('/', (req, res) => { res.json({ message: 'GET request' }); }); router.post('/', (req, res) => { res.json({ created: true }); }); router.put('/:id', updateValidation, (req, res) => { res.json({ updated: true }); }); router.delete('/:id', (req, res) => { res.json({ deleted: true }); }); ``` -------------------------------- ### Catch-all Handler with app.all() Source: https://github.com/expressjs/express/blob/master/_autodocs/8-middleware-flow.md Use app.all() to create a handler that matches all HTTP methods for a given path. This is useful for applying middleware to a group of routes. ```javascript app.all('/api/*', (req, res, next) => { console.log('Any API request'); next(); }); app.get('/api/users', (req, res) => { res.json([]); }); // GET /api/users // 1. app.all handler logs "Any API request" // 2. app.get handler responds ``` -------------------------------- ### View Constructor Source: https://github.com/expressjs/express/blob/master/_autodocs/4-view.md Creates a new View instance for a template file, configuring lookup paths and engines. ```APIDOC ## new View(name, options) ### Description Creates a new View instance for a template file, configuring lookup paths and engines. ### Parameters #### Path Parameters - **name** (string) - Required - Template file name (with or without extension) - **options** (object) - Required - Configuration object ##### Options - **defaultEngine** (string) - Optional - Default template engine extension (e.g., `'ejs'`) - **engines** (object) - Required - Template engine cache object (maps extensions to engine functions) - **root** (string or string[]) - Required - Root directory or directories for view lookup ### Throws - Error if no file extension is provided and no `defaultEngine` is specified - Error if the required template engine module is not available or doesn't export `__express` ### Example ```javascript const View = require('express/lib/view'); const view = new View('user', { defaultEngine: 'ejs', engines: {}, root: '/path/to/views' }); ``` ``` -------------------------------- ### View Instance Extension Property - Default Engine Source: https://github.com/expressjs/express/blob/master/_autodocs/4-view.md Retrieves the file extension using the defaultEngine option when the filename lacks an extension. ```javascript const view = new View('index', { defaultEngine: 'hbs', /* ... */ }); console.log(view.ext); // '.hbs' ```