-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
200 lines (153 loc) · 4.68 KB
/
app.js
File metadata and controls
200 lines (153 loc) · 4.68 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
// Import the express module
import express from "express";
import mysql2 from "mysql2";
import dotenv from "dotenv";
dotenv.config();
const pool = mysql2
.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
})
.promise();
// Create an instance of an Express application
const app = express();
app.set("view engine", "ejs");
// Enable static files serving
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
// Define the port number where our server will listen
const contacts = [];
const PORT = 3111;
// Define a default "route" ('/')
// req: contains information about the incoming request
// res: allows us to send back a response to the client
app.get("/db-test", async (req, res) => {
try {
const [contacts] = await pool.query("SELECT * FROM contacts");
res.send(contacts);
} catch (err) {
console.error("Database Error:", err);
res.status(500).send("Database error: " + err.message);
}
});
app.get("/", (req, res) => {
res.render("home");
});
app.post("/confirm", async (req, res) => {
try {
// Get form data from req.body
const contact = req.body;
// Log the contact data (for debugging)
console.log("New contact submitted:", contact);
// SQL INSERT query with placeholders to prevent SQL injection
const sql = `INSERT INTO contacts(fname, lname, email, met, metInfo, message, format)
VALUES (?, ?, ?, ?, ?, ?, ?);`;
// Parameters array must match the contact of ? placeholders
// Make sure your property names match your contact names
const params = [
contact.fname,
contact.lname,
contact.email,
contact.met,
contact.metInfo,
contact.message,
contact.format,
];
// Execute the query and grab the primary key of the new row
const [result] = await pool.execute(sql, params);
console.log("Contact saved with ID:", result.insertId);
// Render confirmation page with the adoption data
res.render("confirmation", { contact });
} catch (err) {
console.error("Error saving contact:", err);
res
.status(500)
.send(
"Sorry, there was an error processing your contact. Please try again."
);
}
res.render("confirmation");
});
app.get("/admin", async (req, res) => {
try {
const [contacts] = await pool.query("SELECT * FROM contacts");
pool.query("SELECT * FROM contacts ORDER BY timestamp DESC");
contacts.forEach((contact) => {
contact.formattedTimestamp = new Date(contact.timestamp).toLocaleString(
"en-US",
{
year: "numeric",
month: "short",
day: "numeric",
hour: "numeric",
hour12: true,
timeZoneName: undefined,
}
);
});
res.render("admin", { contacts });
} catch (err) {
console.error("Database Error:", err);
res.status(500).send("Database error: " + err.message);
}
});
app.get("/contact", (req, res) => {
res.render("contact");
});
// const contact = {
// fname: req.body.fname,
// lname: req.body.lname,
// email: req.body.email,
// meet: req.body.meet,
// message: req.body.message,
// format: req.body.format,
// timestamp: new Date().toLocaleString(),
// };
app.post("/submit-form", async (req, res) => {
try {
const contact = req.body;
contact.timestamp = new Date();
if (contact.format == null || contact.format == undefined) {
contact.format = '';
}
console.log("New contact recieved:", contact);
const sql = `INSERT INTO contacts
(fname, lname, email, met, metInfo, message, format, timestamp)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;
const params = [
contact.fname,
contact.lname,
contact.email,
contact.met,
contact.metInfo,
contact.message,
contact.format,
contact.timestamp,
];
const [result] = await pool.execute(sql, params);
console.log("Contact inserted with ID:", result.insertId);
res.render("confirmation", { contact: contact });
} catch (err) {
console.error("Error inserting contact:", err);
if (err.code === "ER_DUP_ENTRY") {
res.status(409).send("A contact with this email already exists.");
} else {
res
.status(500)
.send(
"Sorry, there was an error processing your contact. Please try again."
);
}
}
});
app.post("/close-form", (req, res) => {
res.render("home");
});
// start the server and make it listen on the port
// specified above
app.listen(PORT, () => {
console.log(`Sever is running at http://localhost:${PORT}`);
});