-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
53 lines (43 loc) · 1.45 KB
/
index.js
File metadata and controls
53 lines (43 loc) · 1.45 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
import express from "express";
import bodyParser from "body-parser";
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const app = express();
const port = 3000;
let posts = [];
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
app.get("/", (req, res) => {
res.render("index.ejs", { posts });
});
app.post("/post", (req, res) => {
const {title, content } = req.body;
const newPost = { id: posts.length + 1, title, content };
posts.push(newPost);
res.redirect("/");
});
app.get("/post/:id/edit", (req, res) => {
const postId = parseInt(req.params.id);
const postToEdit = posts.find(post => post.id === postId);
res.render("edit", { post: postToEdit});
});
app.post("/post/:id/edit", (req, res) => {
const postId = parseInt(req.params.id);
const updatedTitle = req.body["title"];
const updatedContent = req.body["content"];
const postToUpdate = posts.find(post => post.id === postId);
postToUpdate["title"] = updatedTitle;
postToUpdate["content"] = updatedContent;
res.redirect("/");
});
app.get("/post/:id/delete", (req, res) => {
const postId = parseInt(req.params.id);
posts = posts.filter(post => post.id !== postId);
res.redirect('/');
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});