Express.js is a minimal web framework for Node.js that makes it easy to build REST APIs. At its core, Express lets you define routes - functions that respond to specific HTTP requests.
When building an API, you'll typically handle different HTTP methods (GET, POST, PUT, DELETE) on various URL paths. Each route consists of three parts: the HTTP method, the path pattern, and a handler function that processes the request and sends a response.
The handler function receives two important objects: req (request) containing data from the client, and res (response) for sending data back. The request object includes the URL parameters, query strings, headers, and body data. The response object provides methods like res.json() to send JSON responses.
Middleware is a key Express concept - functions that run before your route handlers. Middleware can modify the request/response objects, perform authentication, parse request bodies, or handle errors. The express.json() middleware, for example, automatically parses incoming JSON data and makes it available on req.body.
Express apps are typically structured by defining middleware first, then routes, and finally exporting the app for testing or starting a server. This modular approach makes your API easy to test and maintain.
1import express from 'express';
2
3const app = express();
4
5// Middleware runs before route handlers
6app.use(express.json());
7
8// Route handler for GET requests
9app.get('/users', (req, res) => {
10 const users = [{ id: 1, name: 'Alice' }];
11 res.json(users);
12});
13
14// Route handler for POST requests
15app.post('/users', (req, res) => {
16 const newUser = req.body; // Available due to middleware
17 res.status(201).json({ id: 2, ...newUser });
18});