Express.js Routing and CRUD API for Student Management
Express.js Routing Basics
The first example sets up a simple Express.js server with static routes, a dynamic route, and a 404 handler.
const express = require('express');
const app = express();
// Route 1
app.get('/', (req, res) => {
res.send('Home Page');
});
// Route 2
app.get('/about', (req, res) => {
res.send('About Page');
});
// Route 3: Dynamic route
app.get('/users/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
// 404 handler: Keep it last
app.use((req, res) => {
res.status(404).send('404 - Page Not Found');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});Building a RESTful Student API
The second example implements a RESTful API for managing students, supporting all four CRUD operations.
const express = require('express');
const app = express();
app.use(express.json());
let students = [
{ id: 1, name: 'John', age: 20 },
{ id: 2, name: 'Jane', age: 22 }
];
// GET: Read all students
app.get('/students', (req, res) => {
res.json(students);
});
// GET: Read student by ID
app.get('/students/:id', (req, res) => {
const student = students.find(
s => s.id === Number(req.params.id)
);
if (!student) {
return res.status(404).send('Student not found');
}
res.json(student);
});
// POST: Create a student
app.post('/students', (req, res) => {
const student = {
id: students.length
? Math.max(...students.map(s => s.id)) + 1
: 1,
name: req.body.name,
age: req.body.age
};
students.push(student);
res.status(201).json(student);
});
// PUT: Update a student
app.put('/students/:id', (req, res) => {
const student = students.find(
s => s.id === Number(req.params.id)
);
if (!student) {
return res.status(404).send('Student not found');
}
student.name = req.body.name ?? student.name;
student.age = req.body.age ?? student.age;
res.json(student);
});
// DELETE: Delete a student
app.delete('/students/:id', (req, res) => {
const index = students.findIndex(
s => s.id === Number(req.params.id)
);
if (index === -1) {
return res.status(404).send('Student not found');
}
const deleted = students.splice(index, 1);
res.json(deleted[0]);
});
// 404 handler
app.use((req, res) => {
res.status(404).send('Route not found');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});Key Takeaways
- Routes map HTTP methods and URL paths to handler functions.
- Dynamic parameters such as
:idare read fromreq.params. - The
express.json()middleware parses incoming JSON request bodies. - The 404 handler must be registered after all other routes.
English with a size of 2.83 KB