Logo hdtoledo
hdtoledo.dev
Módulos_del_Sistema
MÓDULO_TEÓRICO

Building the Bridge (Backend)

Building the Bridge (Backend)

Building the Bridge (The Waiter)

The "Counter" (Frontend) we made in the last lesson is very nice, but it is incapable of saving data. If Doña Pepa clicks "Save", absolutely nothing happens. We need to hire our star employee: The Backend.

This employee will stand between the Counter and the Vault (Database). To create it, we will use a technology called Node.js.


1. What is Node.js and how is it prepared?

Node.js is an environment that allows JavaScript to live outside the browser. We can use the same language as the Frontend to control our server!

Quick Installation:

  1. Download it at nodejs.org (always choose the "LTS" version - Long Term Support, it's the most stable).
  2. Open your terminal and verify it's installed by typing node -v.

Starting the Project: Open a new folder in your terminal and type:

bash
npm init -y

This creates a package.json file. It's like your employee's "ID card", where we will note down the tools he needs to work.


2. The Waiter's Tools (Libraries)

So that our Backend doesn't have to do everything from scratch, we will install "magic tools" called libraries:

bash
npm install express cors dotenv mysql2
  • express: It's the waiter's uniform and tray. It allows us to create the web server in 3 lines of code.
  • cors: It's the security pass. Without this, the browser will block the Counter when trying to talk to the Waiter.
  • dotenv: A tiny secret vault to hide our passwords.
  • mysql2: The dictionary. It allows Node.js to speak the "SQL" language to communicate with our MySQL Database (we will use XAMPP in this case).

3. The Secrets File (.env)

To connect to the database securely, we must never put passwords directly in our source code! Instead, we use a hidden environment file.

Create a file named exactly .env (with the dot at the beginning) in the same folder as your project, and write the following inside:

env
# Example for PostgreSQL (adjust with your real data) DATABASE_URL=postgresql://postgres:your_secret_password@localhost:5432/dona_pepa_store # If you use XAMPP (MySQL/MariaDB), the default user is "root" and has NO password: # DATABASE_URL=mysql://root:@localhost:3306/dona_pepa_store

Note: Change postgres, your_secret_password and dona_pepa_store for your actual user, password, and database name. If you use XAMPP with MySQL, make sure to install the correct library (npm install mysql2) and use the mysql URL.


4. Code: Bringing the Server to Life

Create a file called server.js and write the following code. This will be the brain of your Backend for now (we will expand it in the next lesson to connect to the DB):

javascript
// 1. Call the tools require('dotenv').config(); // This magically reads your .env file const express = require('express'); const cors = require('cors'); const app = express(); // 2. Configure behavior (Best Practices) app.use(cors()); // Allow the Frontend to talk to us app.use(express.json()); // Understand data arriving in JSON format // 3. Create the waiter's "Ear" (The Route or Endpoint) app.post('/api/products', (req, res) => { // We receive the data the Frontend sent in the request const { name, price } = req.body; // BEST PRACTICE: BACKEND VALIDATION! (Real Security) if (!name || price < 0) { return res.status(400).send({ error: "Invalid data, hacker 🕵️‍♂️" }); } console.log(`Order received! They want to register ${name} at $${price}`); // For now, we just reply that everything is fine. // (In the next lesson we will replace this with the SQL INSERT INTO) res.status(201).send({ message: "Product validated by the Backend!" }); }); // 4. Wake up the Waiter const PORT = 3000; app.listen(PORT, () => { console.log(`🚀 Doña Pepa's Waiter is listening for orders on port ${PORT}`); });

5. Starting the Engines

To turn on your Waiter, go to your terminal and type:

bash
node server.js

You will see the message with the little rocket. Your server is now running and waiting for orders!

Conclusion: Our Waiter is alive, listening, and secure! In the final lesson (Final Integration), we will write the complete server.js code so the Counter can send the message, the Waiter can receive it, and execute the real INSERT INTO in the Database.