-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
78 lines (70 loc) · 2.41 KB
/
server.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
let notes = [];
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/add-note', (req, res) => {
const { title, content } = req.body;
if (title && content) {
const note = { id: notes.length + 1, title, content };
notes.push(note);
res.send(`
<li id="note-${note.id}">
<h2>${note.title}</h2>
<p>${note.content}</p>
<button class="edit-button" hx-get="/edit-note/${note.id}">Edit</button>
<button class="delete-button" hx-delete="/delete-note/${note.id}">Delete</button>
</li>
`);
} else {
res.status(400).send('Title and content are required');
}
});
app.get('/edit-note/:id', (req, res) => {
const noteId = parseInt(req.params.id);
const note = notes.find(n => n.id === noteId);
if (note) {
res.send(`
<li id="note-${note.id}">
<form hx-put="/update-note/${note.id}">
<input type="text" name="title" value="${note.title}" required>
<textarea name="content" required>${note.content}</textarea>
<button type="submit">Update</button>
</form>
</li>
`);
} else {
res.status(404).send('Note not found');
}
});
app.put('/update-note/:id', (req, res) => {
const noteId = parseInt(req.params.id);
const { title, content } = req.body;
const note = notes.find(n => n.id === noteId);
if (note) {
note.title = title;
note.content = content;
res.send(`
<li id="note-${note.id}">
<h2>${note.title}</h2>
<p>${note.content}</p>
<button class="edit-button" hx-get="/edit-note/${note.id}">Edit</button>
<button class="delete-button" hx-delete="/delete-note/${note.id}">Delete</button>
</li>
`);
} else {
res.status(404).send('Note not found');
}
});
app.delete('/delete-note/:id', (req, res) => {
const noteId = parseInt(req.params.id);
notes = notes.filter(n => n.id !== noteId);
res.send('');
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});