Final Integration: Pepa's Success

Final Integration: The System in Action
The big day has arrived. We have a beautiful Counter (HTML/CSS), we have our star Waiter listening (Node.js/Express), and we have an indestructible Vault (SQL Database).
Now, we are going to turn on the entire system. We will make the Frontend, Backend, and Database talk to each other to achieve the first automated web record of Doña Pepa's store.
Step 1: The Counter Makes a Call (Frontend)
For the Counter to talk to the Waiter, we need to use a special JavaScript function called fetch(). It's like picking up the phone and making a call.
Let's go back to our Counter's JavaScript code (Lesson 12) and add the call:
javascript// In the Frontend (Browser) const form = document.getElementById('product-form'); form.addEventListener('submit', async function(event) { event.preventDefault(); // 1. We take what Pepa typed const productName = document.getElementById('name').value; const productPrice = document.getElementById('price').value; // 2. We call the Waiter (Backend) on port 3000 try { const response = await fetch('http://localhost:3000/api/products', { method: 'POST', // We want to "send" information headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: productName, price: productPrice }) }); if (response.ok) { alert('Product saved successfully in the vault!'); form.reset(); // We clear the form } } catch (error) { alert('The Waiter is not responding. Check if the server is turned on.'); } });
Step 2: The Waiter Opens the Vault (The Complete server.js Code)
The Waiter receives the call. The data is correct. Now, he needs to open the vault and do an INSERT INTO.
Below you have the complete and final code for your server.js file. Replace your old code with this one. Notice that here we integrate the pg library (PostgreSQL) and use the secret credentials from our .env:
javascript// --- server.js (COMPLETE CODE) --- require('dotenv').config(); // Loads your connection from the .env file const express = require('express'); const cors = require('cors'); const mysql = require('mysql2/promise'); // MySQL Database library const app = express(); // Basic configuration app.use(cors()); app.use(express.json()); // We connect to the Vault (Database)! const pool = mysql.createPool(process.env.DATABASE_URL); // Route to receive products from the Counter (Frontend) app.post('/api/products', async (req, res) => { const { name, price } = req.body; // We validate for security... if (!name || price < 0) { return res.status(400).send("Invalid data"); } try { // THE WAITER SPEAKS SQL 🗣️ // He passes the order directly to the database securely const result = await pool.query( 'INSERT INTO Products (name, price) VALUES (?, ?)', [name, price] // We pass the values securely (Parameterized) ); // We let the Counter know everything went well res.status(201).send({ message: "Saved in DB", product_id: result[0].insertId }); } catch (error) { console.error("Error in the vault:", error); res.status(500).send("Server error"); } }); const PORT = 3000; app.listen(PORT, () => { console.log(`🚀 Doña Pepa's Waiter is listening for orders on port ${PORT}`); });
Make sure you have your database server running and then restart your Node server using
node server.js.
💡 A Crucial Security Detail: Parameterized Queries
Did you notice that instead of writing the values directly into the SQL query, we put ? and ??
This is called a Parameterized Query.
If an evil hacker tries to put the text Milk; DROP TABLE Products; as the product name, the Node.js library will catch that malicious code, clean it, and save it literally as a harmless, weirdly-named milk. This is your greatest defense against SQL Injection!
🎉 Doña Pepa's Success
Doña Pepa opens her browser. She types "Coastal Cheese" and "5500" into her neon-colored form. She clicks "Save Product".
- The button changes to "Saving..."
- The Frontend sends a
fetch()to the Backend. - The Backend validates the data, connects to MySQL via the
pooland executes theINSERT INTO. - The Database saves the cheese to the hard drive forever.
- And Doña Pepa sees a green success alert!
You did it! You have built a real system from scratch. You started with the chaos of notebooks, modeled tables, applied foreign keys, optimized with indexes, protected with transactions and views, and finally built a complete 3-tier architecture.
Now you have the solid foundations to master any database and build the backend of any modern web application. Keep coding!
