-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
76 lines (66 loc) · 2.54 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
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const sendgrid = require('@sendgrid/mail');
const cors = require('cors'); // Import cors
const app = express();
const PORT = process.env.PORT || 3000;
// Enable CORS for your frontend domain or temporarily allow all origins for testing
app.use(cors({
origin: 'https://www.karacrown.com', // Allow only your frontend in production
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true // If using cookies/auth tokens
}));
// Handle preflight requests
app.options('*', cors());
app.use(bodyParser.json());
// Load API keys and log for debugging
const RECAPTCHA_SECRET_KEY = process.env.RECAPTCHA_SECRET_KEY;
const SENDGRID_API_KEY = process.env.SENDGRID_API_KEY;
if (RECAPTCHA_SECRET_KEY) {
console.log("RECAPTCHA_SECRET_KEY: Loaded");
} else {
console.error("RECAPTCHA_SECRET_KEY is missing!");
}
if (SENDGRID_API_KEY) {
console.log("SENDGRID_API_KEY: Loaded");
sendgrid.setApiKey(SENDGRID_API_KEY);
} else {
console.error("SENDGRID_API_KEY is missing!");
}
app.post('/verify-recaptcha', async (req, res) => {
const { token, name, email, message } = req.body;
try {
// Verify the reCAPTCHA token with Google's API
const response = await axios.post('https://www.google.com/recaptcha/api/siteverify', null, {
params: {
secret: RECAPTCHA_SECRET_KEY,
response: token
}
});
if (response.data.success) {
console.log("reCAPTCHA verification successful");
// Send an email using SendGrid
const msg = {
to: '[email protected]',
from: '[email protected]',
subject: 'New Contact Form Submission',
text: `Name: ${name}\nEmail: ${email}\nMessage: ${message}`
};
await sendgrid.send(msg);
console.log("Email sent successfully");
res.status(200).send({ success: true, message: 'Email sent successfully!' });
} else {
console.error("Invalid reCAPTCHA token", response.data);
res.status(400).send({ success: false, error: 'Invalid reCAPTCHA token' });
}
} catch (error) {
console.error("Error in /verify-recaptcha:", error);
res.status(500).send({ success: false, error: error.message });
}
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});