Implementing CRUD Endpoints
Stryg for at vise menuen
Implementing CRUD Endpoints
CRUD stands for Create, Read, Update, and Delete. These are the four basic operations most APIs perform when working with data.
In Express.js, each CRUD operation is usually connected to a specific HTTP method.
Basic CRUD Example
The following example uses a simple in-memory array instead of a database. This keeps the focus on how Express.js endpoints work.
const express = require('express');
const app = express();
app.use(express.json());
let users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
app.get('/users', (req, res) => {
res.json(users);
});
app.post('/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name
};
users.push(newUser);
res.status(201).json(newUser);
});
app.put('/users/:id', (req, res) => {
const user = users.find(user => user.id === Number(req.params.id));
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
user.name = req.body.name;
res.json(user);
});
app.delete('/users/:id', (req, res) => {
users = users.filter(user => user.id !== Number(req.params.id));
res.json({ message: 'User deleted' });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
How It Works
- The
GET /usersendpoint returns all users; - The
POST /usersendpoint reads data fromreq.body, creates a new user, and returns it with the201status code; - The
PUT /users/:idendpoint usesreq.params.idto find a user and update the user's name; - The
DELETE /users/:idendpoint removes a user from the array and returns a confirmation message; - The
express.json()middleware is important because it allows Express.js to read JSON data from the request body.
Var alt klart?
Tak for dine kommentarer!
Sektion 4. Kapitel 2
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
Sektion 4. Kapitel 2