Server. Js backend

Here is a server.js file for your backend, which connects to a MySQL database and handles a "Contact Us" form submission.


---

Setup Instructions

1. Install required dependencies:

npm init -y
npm install express mysql cors body-parser dotenv


2. Create a .env file for database credentials.


3. Run the server:

node server.js



Final Summary of Changes

✔ Change MySQL credentials in .env
✔ Ensure correct database and table names in server.js
✔ Modify the port if needed

Let me know if you need further customization! 🚀

---

Full Code for server.js

require('dotenv').config();
const express = require('express');
const mysql = require('mysql');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
const PORT = process.env.PORT || 5000;

// Middleware
app.use(cors());
app.use(bodyParser.json());

// MySQL Connection
const db = mysql.createConnection({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_NAME
});

db.connect((err) => {
    if (err) {
        console.error('Database connection failed: ', err);
    } else {
        console.log('Connected to MySQL Database');
    }
});

// Contact Form API - Store Data in MySQL
app.post('/contact', (req, res) => {
    const { name, email, message } = req.body;

    if (!name || !email || !message) {
        return res.status(400).json({ error: 'All fields are required' });
    }

    const query = 'INSERT INTO contact (name, email, message) VALUES (?, ?, ?)';
    db.query(query, [name, email, message], (err, result) => {
        if (err) {
            console.error('Error inserting data:', err);
            return res.status(500).json({ error: 'Database error' });
        }
        res.status(201).json({ message: 'Data submitted successfully' });
    });
});

// Fetch All Contacts API
app.get('/contacts', (req, res) => {
    const query = 'SELECT * FROM contact';
    db.query(query, (err, results) => {
        if (err) {
            console.error('Error fetching data:', err);
            return res.status(500).json({ error: 'Database error' });
        }
        res.status(200).json(results);
    });
});

// Start Server
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});


---

Create .env file for Environment Variables

DB_HOST=localhost
DB_USER=root
DB_PASS=yourpassword
DB_NAME=connection_of_database_to_php
PORT=5000


---

Create MySQL Table (connection Database)

CREATE DATABASE connection_of_database_to_php;

USE connection_of_database_to_php;

CREATE TABLE contact (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL,
    message TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);


---

This server.js file: ✅ Connects to MySQL
✅ Receives contact form data via POST /contact
✅ Fetches all submitted data via GET /contacts
✅ Uses .env file for credentials
✅ Runs on port 5000

Let me know if you need modifications!

Comments

Popular posts from this blog

Petroleum