-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
56 lines (41 loc) · 1.36 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
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(bodyParser.json());
mongoose
.connect("mongodb://localhost:27017", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("Connected to MongoDB"))
.catch((error) => console.error("Error connecting to MongoDB:", error));
const clickSchema = new mongoose.Schema({
action: { type: String, required: true },
timestamp: { type: Date, required: true },
});
const Click = mongoose.model("Click", clickSchema);
app.get("/", (req, res) => {
res.send("Welcome to the Click Logger API!");
});
app.post("/log-click", async (req, res) => {
const { action, timestamp } = req.body;
if (!action || !timestamp) {
return res.status(400).json({ error: "Action and timestamp are required." });
}
try {
const newClick = new Click({ action, timestamp });
await newClick.save();
res.status(201).json({ message: "Click logged successfully!" });
} catch (error) {
console.error("Error saving click:", error);
res.status(500).json({ error: "Failed to log click." });
}
});
app.listen(PORT, () => {
console.log(`Server is running on https://love-bundle.onrender.com`);
});