-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
83 lines (73 loc) · 2.1 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
79
80
81
82
83
import express from "express";
import bodyParser from "body-parser";
import axios from "axios";
const app = express();
const port = 3000;
const API_URL = "http://localhost:4000";
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Route to render the main page
app.get("/", async (req, res) => {
try {
const response = await axios.get(`${API_URL}/posts`);
console.log(response);
res.render("index.ejs", { posts: response.data });
} catch (error) {
res.status(500).json({ message: "Error fetching posts" });
}
});
// Route to render the edit page
app.get("/new", (req, res) => {
res.render("modify.ejs", { heading: "New Post", submit: "Create Post" });
});
app.get("/edit/:id", async (req, res) => {
try {
const response = await axios.get(`${API_URL}/posts/${req.params.id}`);
console.log(response.data);
res.render("modify.ejs", {
heading: "Edit Post",
submit: "Update Post",
post: response.data,
});
} catch (error) {
res.status(500).json({ message: "Error fetching post" });
}
});
// Create a new post
app.post("/api/posts", async (req, res) => {
try {
const response = await axios.post(`${API_URL}/posts`, req.body);
console.log(response.data);
res.redirect("/");
} catch (error) {
res.status(500).json({ message: "Error creating post" });
}
});
// Partially update a post
app.post("/api/posts/:id", async (req, res) => {
console.log("called");
try {
const response = await axios.patch(
`${API_URL}/posts/${req.params.id}`,
req.body
);
console.log(response.data);
res.redirect("/");
} catch (error) {
console.log(error)
res.status(500).json({ message: "Error updating post" });
}
});
// Delete a post
app.get("/api/posts/delete/:id", async (req, res) => {
try {
await axios.delete(`${API_URL}/posts/${req.params.id}`);
res.redirect("/");
} catch (error) {
res.status(500).json({ message: "Error deleting post" });
}
});
app.listen(port, () => {
console.log(`Backend server is running on http://localhost:${port}`);
});