Express.js β Routing and CRUD
After completing this topic
You will be able to launch a web server with Express.js and set up routing to send different responses for each URL path. You will also be able to implement the four basic operations (CRUD) of a REST API.
Why use Express.js?
You can create a server using Node.js's built-in http module. However, you would have to implement URL branching, parameter parsing, and error handling yourself. Express.js is a web framework that handles these repetitive tasks for you.
# Installationnpm init -ynpm install express// app.js β The simplest Express server
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello!');
});
app.listen(3000, () => {
console.log('Server running: http://localhost:3000');
});Running node app.js allows you to access localhost:3000 in your browser. These six lines are all that Express requires; the rest is simply a repetition and extension of this pattern.
Routing β Connecting URLs to Functions
Routing is the rule: "When a request comes to this URL, execute this function."
// GET β Data retrieval
app.get('/users', (req, res) => {
res.json([{ id: 1, name: 'Kim Hun' }, { id: 2, name: 'Lee Soo' }]);
});
// GET β Retrieving a specific item using a URL parameter
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.json({ id: userId, name: 'Kim Hun' });
});
// POST β Data creation
app.use(express.json()); // Parsing JSON request body is required
app.post('/users', (req, res) => {
const newUser = req.body;
res.status(201).json({ message: 'Creation complete', user: newUser });
});:id is a dynamic parameter. Both /users/1 and /users/42 match this route, and you can retrieve the value using req.params.id.
CRUD β The Four Basic Operations
Almost all data processing in web applications boils down to these four operations.
| Operation | HTTP Method | URL Example | Description |
|---|---|---|---|
| Create | POST | /users | Create a new user |
| Read | GET | /users or /users/:id | List or retrieve a single item |
| Update | PUT | /users/:id | Modify specific user information |
| Delete | DELETE | /users/:id | Delete a specific user |
// Update β Data modification
app.put('/users/:id', (req, res) => {
const { id } = req.params;
const updatedData = req.body;
res.json({ message: `User ${id} updated`, data: updatedData });
});
// Delete β Data deletion
app.delete('/users/:id', (req, res) => {
const { id } = req.params;
res.json({ message: `User ${id} deleted` });
});This pattern is called a REST API. The URL represents "what" (a noun), and the HTTP method represents "how" (a verb). It is a structure where the four operations (GET, POST, PUT, and DELETE) are mapped to a single URL like /users.
Separating Routes β When files get too large
When you have many routes, you cannot put them all in a single app.js file. Use Express's Router to separate them into files.
// routes/users.js
const router = require('express').Router();
router.get('/', (req, res) => { res.json([]); });
router.post('/', (req, res) => { res.status(201).json({}); });
router.put('/:id', (req, res) => { res.json({}); });
router.delete('/:id', (req, res) => { res.json({}); });
module.exports = router;// app.js β Mount the router
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
// /users + router's internal '/' = GET /users
// /users + router's internal '/:id' = PUT /users/42app.use('/users', usersRouter) is the key. All requests starting with /users are handled by routes/users.js. This is a practical application of the previous topic (code modularization).
Key Takeaways
Express is all about connecting "URL β function." Middleware, authentication, and database integration are built on top of this simple structure, but the fundamental principle remains the same. Mastering the four CRUD patterns will enable you to create most backend APIs.
β Apply to bio: DevBench β Express Basics