-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
52 lines (43 loc) · 1.13 KB
/
Copy pathapp.js
File metadata and controls
52 lines (43 loc) · 1.13 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
import express from "express";
import bodyParser from "body-parser";
import { v4 as uuidv4 } from "uuid"; // for unique IDs
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
let posts = [];
// Home - view posts
app.get("/", (req, res) => {
res.render("index", { posts: posts });
});
// Create post
app.post("/create", (req, res) => {
const newPost = {
id: uuidv4(),
title: req.body.title,
content: req.body.content
};
posts.push(newPost);
res.redirect("/");
});
// Edit form
app.get("/edit/:id", (req, res) => {
const post = posts.find(p => p.id === req.params.id);
res.render("edit", { post: post });
});
// Handle edit
app.post("/edit/:id", (req, res) => {
const post = posts.find(p => p.id === req.params.id);
post.title = req.body.title;
post.content = req.body.content;
res.redirect("/");
});
// Delete
app.post("/delete/:id", (req, res) => {
posts = posts.filter(p => p.id !== req.params.id);
res.redirect("/");
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});