Implementing CRUD Endpoints
メニューを表示するにはスワイプしてください
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.
すべて明確でしたか?
フィードバックありがとうございます!
セクション 4. 章 2
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 4. 章 2