-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
91 lines (81 loc) · 2.44 KB
/
server.js
File metadata and controls
91 lines (81 loc) · 2.44 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
require("dotenv").config();
const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
const PORT = process.env.PORT || 5000;
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "Public")));
// DATABASE CONNECTION
mongoose
.connect(process.env.MONGO_URI)
.then(() => console.log("✅ MongoDB Connection Successful (Atlas)"))
.catch((err) => console.error("❌ MongoDB Connection Error:", err));
// DATABASE SCHEMA
const contactSchema = new mongoose.Schema({
name: String,
email: String,
mobile: String,
message: String,
date: {
type: String,
default: () => {
const now = new Date();
return now.toLocaleString("en-GB", {
hour12: false,
timeZone: "Asia/Kolkata",
weekday: "short",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
}).replace(",", "");
},
},
});
const Contact = mongoose.model("Contact", contactSchema);
// Serve HTML Pages
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "views", "index.html"));
});
app.get("/admin.html", (req, res) => {
res.sendFile(path.join(__dirname, "views", "admin.html"));
});
app.get("/jhufdyrbbfh874hhyehfg", (req, res) => {
res.sendFile(path.join(__dirname, "views", "dashboard.html"));
});
app.get("/thank.html", (req, res) => {
res.sendFile(path.join(__dirname, "views", "thank.html"));
});
// FORM SUBMISSION ROUTE
app.post("/submit-form", async (req, res) => {
const { name, email, mobile, message } = req.body;
const newContact = new Contact({ name, email, mobile, message });
try {
await newContact.save();
console.log(newContact);
res.redirect("/thank.html");
} catch (error) {
console.error("❌ Error saving data: ", error);
res.status(500).send("Error saving data.");
}
});
// FETCH DATA FOR ADMIN PANEL
app.get("/get-submissions", async (req, res) => {
try {
const submissions = await Contact.find({}).sort({ date: -1 });
res.json(submissions);
} catch (error) {
console.error("❌ Error fetching data:", error);
res.status(500).send("Error fetching data.");
}
});
// Start the server
app.listen(PORT, () => {
console.log(`🚀 Server is running on http://localhost:${PORT}`);
});