-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
60 lines (51 loc) · 1.5 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const express = require('express');
const app = express();
const port = 4000;
app.use(express.json());
let items = [];
// Serve the index.html file on the root path
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/items', (req, res) => {
const newItem = req.body;
newItem.id = Date.now();
items.push(newItem);
res.status(201).json(newItem);
});
app.get('/items', (req, res) => {
res.json(items);
});
app.get('/items/:id', (req, res) => {
const id = req.params.id; // Error: Missing parseInt to convert the ID to a number
const item = items.find(item => item.id === id);
if (item) {
res.json(item);
} else {
res.status(404).json({ error: "Item not found" });
}
});
app.put('/items/:id', (req, res) => {
const id = parseInt(req.params.id);
const updatedItem = req.body;
const index = items.findIndex(item => item.id === id);
if (index !== -1) {
items[index] = updatedItem;
res.json(updatedItem);
} else {
res.status(404).json({ error: "Item not found" });
}
});
app.delete('/items/:id', (req, res) => {
const id = parseInt(req.params.id);
const index = items.findIndex(item => item.id === id);
if (index !== -1) {
items.splice(index, 1);
res.json({ message: "Item deleted" });
} else {
res.status(404).json({ error: "Item not found" });
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});