1. What is Express?
Express.js is a minimal and flexible web application framework for Node.js.
It is designed to build web applications and APIs efficiently by providing essential features
through middleware and routing.
Key Features:
• Lightweight and fast
• Middleware support
• Robust routing
• Easily integrates with databases and other tools
2. Routing in Express
What is Routing?
Routing refers to how an application responds to a client request to a particular endpoint,
which is defined by a URL path and an HTTP method.
Basic Route Example
app.get('/hello', (req, res) => {
res.send('Hello World!');
});
• GET is the HTTP method.
• /hello is the route path.
• The callback function handles the request and sends a response.
Route Parameters
Used to capture dynamic values from the URL.
app.get('/customers/:customerId', (req, res) => {
res.send(`Customer ID: ${req.params.customerId}`);
});
Example:
• URL: /customers/1234
• Output: Customer ID: 1234
• req.params.customerId = 1234
3. Express Request Matching and Order
• Routes are matched in the order they are defined.
• More specific routes should be defined before more generic ones.
Example
app.get('/api/issues', handler); // Specific route
app.use('/api/*', middleware); // Generic route
• Requests to /api/issues will be handled by the first route.
• All other /api/* requests will be passed to the middleware.
4. Built-in Middleware in Express
Middleware functions have access to the request object (req), the response object (res), and
the next function in the application’s request-response cycle.
express.static
Used to serve static files such as HTML, CSS, images, etc.
Example
app.use(express.static('public'));
• Allows access to files like:
o /index.html
o /style.css
o /image.png
• These files must be placed in the public folder.
Path-Specific Middleware
app.use('/public', express.static('public'));
• Static files must be accessed like:
o /public/index.html
o /public/style.css