Registration form

📋 Registration Flow (Step-by-Step)

🧱 1. User filled form and click submit button

You have a form with fields like usernamepasswordemail, etc.


🧠 2. JavaScript: Validate Data

function validateRegister() {
const username = document.getElementById("reg-username").value;
// ... more fields

// Simple validation
if (username.length < 3) {
alert("Username too short!");
return false;
}

const registrationData = { username, firstname, lastname, password, email, country };
registerUser(registrationData); // Go talk to the server
return false; // Stop form from reloading the page
}

🚀 3. JavaScript Sends the Data

✅ If valid → Calls registerUser(data)
Sends the form data to the backend API /api/register

async function registerUser(data) {
const response = await fetch("/api/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});

if (response.ok) {
alert("Registered! Redirecting to login...");
window.location.href = "login"; // Go to login page
} else {
alert("Something went wrong!");
}
}

🧠 4. What Happens on the Server (Node.js + Express)

app.post("/api/register", async (req, res) => {
const { username, email, password } = req.body;

// Hash password
const hashedPassword = await bcrypt.hash(password, 10);

// Store in MySQL
const query = "INSERT INTO users (...) VALUES (...)";
await executeQuery(query, [...]);

res.status(201).json({ message: "Success!" });
});

🖥️ On the Server (Node.js)

  1. Express reads the form data using req.body
  2. Validates all fields are present
  3. Password is hashed using bcrypt
  4. SQL Insert into the users table
INSERT INTO users (...) VALUES (...hashed password...)

🔐 If successful:

  • Responds with: { message: "Registration successful!" }
  • JS redirects to login page

❌ If duplicate username/email:

  • Sends 409 Conflict: "Username or email already exists."