-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
72 lines (58 loc) · 1.93 KB
/
index.js
File metadata and controls
72 lines (58 loc) · 1.93 KB
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
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
const app = express();
const port = 3000;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
// Middle ware to parse the json data
app.use(express.json());``
// Middleware to parse URL-encoded form data
app.use(express.urlencoded({ extended: true }));
// Set the view engine to ejs
app.set('view engine', 'ejs');
// array of messages
let pageMessages = [];
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'chat.html'));
res.status(200);
});
app.post('/', (req, res) => {
const title = req.body.title;
const username = req.body.username;
const message = req.body.message;
const date = new Date();
if(!title || !username || !message) {
return res.status(400).send("Username and message are required");
}
pageMessages.push({ _id: Date.now().toString(), title, username, message, date });
res.redirect('/blogpost');
});
app.get("/blogpost", (req, res) => {
res.render('displayMessage', { messages: pageMessages });
});
// Delete post path
app.delete('/post/:id', (req, res) => {
const postId = req.params.id;
pageMessages = pageMessages.filter(msg => msg._id !== postId);
res.status(200).json({ success: true });
});
// Edit post path
app.put('/post/:id', (req, res) => {
const postId = req.params.id;
const { title, username, message } = req.body;
const post = pageMessages.find(msg => msg._id === postId);
if (post) {
post.title = title;
post.username = username;
post.message = message;
res.status(200).json({ success: true });
} else {
res.status(404).send("Post not found");
}
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});