const express = require('express');
const app = express();
const PORT = 8080;
app.use(express.json());
let users = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 },
];
app.get('/api/users', (req, res) => {
res.json(users);
});
app.get('/api/users/:id', (req, res) => {
const userId = parseInt(req.params.id, 10);
const user = users.find(u => u.id === userId);
if (user) {
res.json(user);
} else {
res.status(404).send('用户未找到');
}
});
app.post('/api/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name,
age: req.body.age,
};
users.push(newUser);
res.status(201).json(newUser);
});
app.put('/api/users/:id', (req, res) => {
const userId = parseInt(req.params.id, 10);
const user = users.find(u => u.id === userId);
if (user) {
user.name = req.body.name || user.name;
user.age = req.body.age || user.age;
res.json(user);
} else {
res.status(404).send('用户未找到');
}
});
app.delete('/api/users/:id', (req, res) => {
const userId = parseInt(req.params.id, 10);
const userIndex = users.findIndex(u => u.id === userId);
if (userIndex !== -1) {
const deletedUser = users.splice(userIndex, 1);
res.json(deletedUser);
} else {
res.status(404).send('用户未找到');
}
});
app.listen(PORT, () => {
console.log(`服务器已启动,访问地址:http://localhost:${PORT}`);
});