Day 5: Express.js Framework
Chapter 5 • Intermediate
Express.js is a fast, unopinionated, minimalist web framework for Node.js. It provides a robust set of features for web and mobile applications.
What is Express.js?
Express is a web application framework that provides a thin layer of fundamental web application features. It simplifies the process of building web applications and APIs.
Key Features:
- Minimal and flexible web application framework
- Robust routing system
- Middleware support for request processing
- Template engine integration
- Static file serving
- Error handling
- HTTP helpers for redirections and caching
Installation and Setup:
Express.js is not a built-in module, so you need to install it using npm. Create a package.json file and install Express as a dependency.
Basic Express Application:
Creating an Express app involves requiring the express module, creating an app instance, defining routes, and starting the server to listen for requests.
Middleware:
Middleware functions are functions that have access to the request object, response object, and the next middleware function. They can execute code, make changes to request/response objects, and end the request-response cycle.
Routing:
Express provides a robust routing system that allows you to define routes based on HTTP methods and URL patterns. You can handle different routes and parameters easily.
Error Handling:
Express has built-in error handling mechanisms. You can define error-handling middleware to catch and handle errors gracefully.
Hands-on Examples
Basic Express Application
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to parse JSON
app.use(express.json());
// Basic route
app.get('/', (req, res) => {
res.send('<h1>Welcome to Express.js!</h1><p>This is a basic Express application.</p>');
});
// Route with parameters
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.json({
message: 'Get user with ID: ' + id + ',',
userId: userId
});
});
// POST route
app.post('/api/users', (req, res) => {
const userData = req.body;
res.status(201).json({
message: 'User created successfully',
user: userData
});
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
// 404 handler
app.use((req, res) => {
res.status(404).json({ error: 'Route not found' });
});
app.listen(PORT, () => {
console.log('Server running on port ' + PORT);
});This example shows a basic Express.js application with routing, middleware, error handling, and JSON parsing capabilities.