-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
70 lines (54 loc) · 1.52 KB
/
index.js
File metadata and controls
70 lines (54 loc) · 1.52 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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const {MongoClient} = require('mongodb');
const dotenv = require('dotenv');
dotenv.config()
const app = express();
app.use(cors());
const PORT = process.env.PORT;``
const CONNECTION_STRING = process.env.CONNECTION_STRING;
const DB_NAME = process.env.DB_NAME;
const client = new MongoClient(CONNECTION_STRING);
async function startServer() {
await client.connect();
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
}
startServer();
// Middleware
app.use(bodyParser.json())
app.get('/',(req,res) => {
res.status(200).send("API is Up");
})
app.post('/form', async (req,res) => {
try{ const {
name,
email,
message
} = req.body
if (
typeof message !== 'string' ||
message.length === 0 ||
message.length > 400 || // Limit length
/[$<>]/.test(message) // Prevent some special characters
) {
return res.status(400).send({ error: "Invalid message input" });
}
const db = client.db(DB_NAME);
const collection = db.collection("reactTravel");
const time = Date.now()
const docToInsert = {
"time": time,
"name": name,
"email": email,
"message": message
}
await collection.insertOne(docToInsert);
res.status(200).send({ success: true });
} catch (error){
console.log("Invalid Input");
return res.status(500).send({ error: "Error generating response" });
}
})