Untitled
unknown
plain_text
8 days ago
1.7 kB
3
Indexable
Never
// Import dependencies const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const dotenv = require('dotenv'); // Load environment variables (optional, for MongoDB URI) dotenv.config(); // Initialize the Express app const app = express(); // Middleware to parse form data (bodyParser) app.use(bodyParser.urlencoded({ extended: true })); // MongoDB connection (offline MongoDB) mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/contactDB', { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => console.log('Connected to MongoDB')) .catch((err) => console.error('MongoDB connection error:', err)); // Define the contact schema and model const contactSchema = new mongoose.Schema({ fullname: String, email: String, message: String, }); const Contact = mongoose.model('Contact', contactSchema); // Route to handle form submission app.post('/submit-form', async (req, res) => { try { // Extract form data const { fullname, email, message } = req.body; // Create a new contact document const contact = new Contact({ fullname, email, message, }); // Save the contact to the MongoDB database await contact.save(); // Send success response res.send('<p class="message">Thank you! Your message has been submitted successfully.</p>'); } catch (error) { console.error('Error saving contact:', error); res.status(500).send('Error saving contact'); } }); // Start the server const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server is running on port ${port}`); });
Leave a Comment