The Express Framework
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It simplifies the process of creating a server by abstracting the low-level http module and providing a powerful Middleware architecture.
Middleware: The Heart of Express
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.
Middleware can:
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware in the stack.
app.use((req, res, next) => {
console.log(`${req.method} request to ${req.url}`);
next(); // Move to the next function
});
Routing and Parameters
Routing defines how an application responds to a client request to a particular endpoint.
- Path Parameters: Used for specific resources (e.g.,
/users/:id). - Query Parameters: Used for filtering or sorting (e.g.,
/search?q=js).
app.get('/api/users/:userId', (req, res) => {
const id = req.params.userId;
const user = database.find(u => u.id === id);
res.status(200).json(user);
});
RESTful Principles
Representational State Transfer (REST) is an architectural style for designing networked applications. It relies on a stateless, client-server, cacheable communications protocol.
| Method | Action | Purpose |
|---|---|---|
| GET | Retrieve | Fetch a resource or list of resources. |
| POST | Create | Create a new resource. |
| PUT/PATCH | Update | Replace or partially update an existing resource. |
| DELETE | Remove | Delete a specified resource. |
Error Handling Middleware
Express distinguishes error-handling middleware by checking the number of arguments. If a function has four arguments (err, req, res, next), Express recognizes it as an error handler.
Environment Configuration
Production applications should never hardcode sensitive data like database URLs or API keys. Express apps typically use the dotenv package to load environment variables from a .env file into process.env.