-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
86 lines (76 loc) · 2.11 KB
/
index.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
79
80
81
82
83
84
85
86
import express from "express";
import bodyParser from "body-parser";
const app = express();
const port = 3000;
const posts = [];
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(port, (req, res) => {
console.log(`Listening on port ${port}`);
});
// Display all posts
app.get('/', (req, res) => {
res.render('index.ejs', { posts });
});
// Display single post
app.get('/post/:postId', (req, res) => {
const postId = req.params.postId;
const post = posts.find(p => p.id === postId);
if (!post) {
res.status(404).send('Post not found');
} else {
res.render('post.ejs', { post });
}
});
// Form for creating post
app.get('/create', (req, res) => {
res.render('create.ejs');
});
// Create post
app.post("/create", (req, res) => {
const { title, subtitle, content } = req.body;
const newPost = {
id: Date.now().toString(),
date: `Posted on ${new Date().toLocaleDateString()}`,
title,
subtitle,
content
};
// console.log(newPost);
posts.push(newPost);
res.redirect('/');
});
// Form for editing an existing post
app.get('/edit/:postId', (req, res) => {
const postId = req.params.postId;
const post = posts.find(p => p.id === postId);
if (!post) {
res.status(404).send('Post not found');
} else {
res.render('edit.ejs', { post });
}
});
// Handle form submission for updating an existing post
app.post('/edit/:postId', (req, res) => {
const postId = req.params.postId;
const { title, content } = req.body;
const index = posts.findIndex(p => p.id === postId);
if (index === -1) {
res.status(404).send('Post not found');
} else {
posts[index].title = title;
posts[index].content = content;
res.redirect('/post/' + postId);
}
});
// Handle form submission for deleting a post
app.post('/delete/:postId', (req, res) => {
const postId = req.params.postId;
const index = posts.findIndex(p => p.id === postId);
if (index === -1) {
res.status(404).send('Post not found');
} else {
posts.splice(index, 1);
res.redirect('/');
}
});