Backend js

Your backend setup is mostly correct, but there are a few improvements and potential fixes you can make:

1. db.js (Database Connection)

  • Use mysql2 instead of mysql for better promise support.
  • Add connection pooling to optimize performance.
  • Handle connection errors more gracefully.

Updated db.js:

const mysql = require("mysql2");

const db = mysql.createPool({
  host: "localhost",
  user: "root",
  password: "",
  database: "contact_form",
  connectionLimit: 10, // Allows multiple concurrent connections
});

// Check database connection
db.getConnection((err, connection) => {
  if (err) {
    console.error("Error connecting to MySQL:", err);
  } else {
    console.log("Connected to MySQL database");
    connection.release(); // Release the connection back to the pool
  }
});

module.exports = db;

2. server.js (Server File)

  • Add error handling for unhandled routes.
  • Use CORS options for better security.

Updated server.js:

const express = require("express");
const cors = require("cors");
const contactRoutes = require("./routes/contactRoutes");

const app = express();
const PORT = 5000;

// Middleware
app.use(cors({ origin: "http://localhost:3000", credentials: true })); // Adjust origin as needed
app.use(express.json());

// Routes
app.use("/api/contacts", contactRoutes);

// Handle undefined routes
app.use((req, res) => {
  res.status(404).json({ error: "Route not found" });
});

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

3. routes/contactRoutes.js (API Routes)

  • Use async/await for cleaner async handling.
  • Add basic validation to avoid empty or invalid data.
  • Improve error messages for better debugging.

Updated routes/contactRoutes.js:

const express = require("express");
const router = express.Router();
const db = require("../db");

// POST: Add a new contact
router.post("/", async (req, res) => {
  try {
    const { name, email, message } = req.body;

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

    const sql = "INSERT INTO contacts (name, email, message) VALUES (?, ?, ?)";
    db.query(sql, [name, email, message], (err, result) => {
      if (err) {
        console.error("Error inserting contact:", err);
        return res.status(500).json({ error: "Failed to add contact" });
      }
      res.status(201).json({ message: "Contact added successfully", id: result.insertId });
    });
  } catch (error) {
    res.status(500).json({ error: "Internal server error" });
  }
});

// GET: Fetch all contacts
router.get("/", async (req, res) => {
  try {
    const sql = "SELECT * FROM contacts";
    db.query(sql, (err, results) => {
      if (err) {
        console.error("Error fetching contacts:", err);
        return res.status(500).json({ error: "Failed to fetch contacts" });
      }
      res.status(200).json(results);
    });
  } catch (error) {
    res.status(500).json({ error: "Internal server error" });
  }
});

module.exports = router;

4. MySQL Database Schema

  • Add created_at timestamp for better tracking.
  • Ensure email is unique to prevent duplicates.

Updated SQL Schema:

CREATE DATABASE contact_form;
USE contact_form;

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

Key Fixes & Improvements:

✅ Switched mysql to mysql2 for better performance.
✅ Used connection pooling to optimize database handling.
✅ Added CORS options for security.
✅ Implemented basic validation in the routes.
✅ Improved error handling and logging for debugging.
✅ Enhanced MySQL schema by making email unique and adding timestamps.

With these changes, your backend will be more efficient, secure, and scalable. Let me know if you need further modifications!

Comments

Popular posts from this blog

Petroleum