Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/brandonvergara1220-del/Mini-Proyecto-Backend-NodeJS/llms.txt

Use this file to discover all available pages before exploring further.

Once the base registration flow is working, the project becomes a solid foundation for practising more advanced Node.js and MySQL concepts. This guide shows concrete, incremental changes — adding a new field, exposing a listing route, and validating input — so you can grow the application one step at a time without reaching for a framework.

Adding a New Form Field

The existing form collects nombre and apellido. Adding an email field requires three coordinated changes: the HTML form, the database schema, and the server-side INSERT query.

1. Update index.html

Add the new input inside the <form> element, between the existing inputs and the submit button:
<form action="recuperardatos" method="post">
  <input type="text"  id="nombre"   name="nombre"   placeholder="Nombre">
  <input type="text"  id="apellido" name="apellido"  placeholder="Apellido">
  <input type="email" id="email"    name="email"     placeholder="Correo electrónico">
  <button type="submit">Enviar</button>
</form>

2. Add the Column to MySQL

Run this statement against the ejemploformulario database to add the column without dropping existing data:
ALTER TABLE usuarios ADD COLUMN email VARCHAR(255);

3. Update the INSERT Query in server.js

Destructure email from the parsed body and include it in the parameterised query:
req.on('end', () => {
  const { nombre, apellido, email } = querystring.parse(body);
  const sql = 'INSERT INTO usuarios (nombre, apellido, email) VALUES (?, ?, ?)';
  conexion.query(sql, [nombre, apellido, email], (err, result) => {
    if (err) throw err;
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end(`Registered: ${nombre} ${apellido} <${email}>`);
  });
});
Always use parameterised placeholders (?) rather than string interpolation to avoid SQL injection.

Adding a GET /usuarios Route

A listing route lets you verify that records are being saved and is useful for debugging during development. Add a new branch to the request handler inside server.js:
} else if (req.method === 'GET' && req.url === '/usuarios') {
  const sql = 'SELECT id, nombre, apellido FROM usuarios ORDER BY created_at DESC';
  conexion.query(sql, (err, rows) => {
    if (err) throw err;
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(rows));
  });
}
With the server running, open http://localhost:3000/usuarios in your browser or use curl:
curl http://localhost:3000/usuarios
You will receive a JSON array of every row in the usuarios table, ordered from newest to oldest:
[
  { "id": 3, "nombre": "Ana",   "apellido": "García" },
  { "id": 2, "nombre": "Luis",  "apellido": "Martínez" },
  { "id": 1, "nombre": "María", "apellido": "López" }
]

Adding Input Validation

Before executing the INSERT, check that the required fields are present and non-empty. Add this guard block right after parsing the request body:
req.on('end', () => {
  const { nombre, apellido } = querystring.parse(body);

  // Validation: both fields must be non-empty strings
  if (!nombre || !apellido || nombre.trim() === '' || apellido.trim() === '') {
    res.writeHead(400, { 'Content-Type': 'text/plain' });
    res.end('Error: nombre and apellido are required.');
    return;
  }

  const sql = 'INSERT INTO usuarios (nombre, apellido) VALUES (?, ?)';
  conexion.query(sql, [nombre.trim(), apellido.trim()], (err, result) => {
    if (err) throw err;
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end(`Registered: ${nombre.trim()} ${apellido.trim()}`);
  });
});
This pattern — validate, then persist — keeps the database clean and makes errors visible to the client with a proper HTTP 400 status code rather than a silent failure or unhandled exception.
As the number of routes and validation rules grows, managing everything inside a single http.createServer callback becomes unwieldy. Consider migrating to Express.js (npm install express) to gain a clean router API, middleware support, and body-parsing utilities out of the box. The conexion.js module works without modification in an Express app — simply require('./conexion') wherever you need it.

Database Structure

Understand the ejemploformulario database schema, table definitions, and column constraints used by this project.

MySQL Setup

Configure MySQL credentials, create the database, and verify the connection settings in conexion.js.

Build docs developers (and LLMs) love