Federico Lelli / SchoolNode.js & Express

NODE.JS · LABORATORIO 02 · UN PASSO ALLA VOLTA

Form, metodi e primi fetch

Prima proviamo ogni metodo da solo. Poi uniamo le operazioni su una nota e introduciamo fetch soltanto nelle ultime due tappe.

Dopo il laboratorio 017 tappe in più incontriForm senza script all’inizioFetch solo alla fine

Prima di iniziare

Completa HTTP, pagine e immagini, compresa la pausa sugli status code. Crea una cartella nuova lab-metodi e un file server.cjs. Ogni tappa fornisce il server completo; quando è indicato di mantenere il server precedente, cambia solo l’HTML. Ferma con Ctrl+C e riavvia dopo le modifiche a Node.

Le tappe 3 e 4 sono esperimenti separati: ognuno riparte dalla propria nota iniziale. Non combinare i frammenti. Solo la tappa 5 li riunisce. Le prove curl si eseguono in un secondo terminale; su macOS/Linux usa curl al posto di curl.exe.

TAPPA 1

POST: un form che invia una richiesta

Ripartiamo da un caso minuscolo. Il form ha soltanto un pulsante. action sceglie l’URL, method="post" sceglie il metodo. Per ora non inviamo campi e non memorizziamo dati: il server conferma soltanto la ricezione.

server.cjs · POST senza dati

const http = require('node:http');

const IP = '127.0.0.1';
const PORT = 3000;

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.end(`<!doctype html>
<html lang="it">
<head>
  <meta charset="utf-8">
  <title>Laboratorio Node.js</title>
</head>
<body>
  <h1>Invia una richiesta POST</h1>
  <form action="/messaggi" method="post">
    <button type="submit">Invia un messaggio</button>
  </form>
</body>
</html>`);
    return;
  }

  if (req.method === 'POST' && req.url === '/messaggi') {
    res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
    res.end('Richiesta POST ricevuta!');
    return;
  }

  if (req.url === '/messaggi') {
    res.writeHead(405, { 'Allow': 'POST' });
    res.end('Per questa rotta usa POST.');
    return;
  }

  if (req.url === '/') {
    res.writeHead(405, { 'Allow': 'GET' });
    res.end('Usa GET per la home.');
    return;
  }

  res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('Pagina non trovata.');
});

server.listen(PORT, IP, () => {
  console.log('Server attivo su http://' + IP + ':' + PORT);
});

Prova nel secondo terminale

curl.exe -i -X POST http://127.0.0.1:3000/messaggi
curl.exe -i http://127.0.0.1:3000/messaggi

Risultato atteso. Apri / e premi il pulsante: il browser naviga alla risposta “Richiesta POST ricevuta!” con stato 200. Scrivere /messaggi nella barra invia GET e restituisce 405. Usiamo 200 perché non abbiamo creato una risorsa.

Tocca a te. Cambia il testo del pulsante e della risposta. Con Network confronta il metodo della home con quello del form.

TAPPA 2

POST: leggere un campo del form

Aggiungiamo un solo dato: il nome. Un form normale invia campi nel formato application/x-www-form-urlencoded, per esempio nome=Ada+Lovelace. L’attributo name="nome" stabilisce il nome del campo trasmesso.

server.cjs · POST con il nome

const http = require('node:http');

const IP = '127.0.0.1';
const PORT = 3000;

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.end(`<!doctype html>
<html lang="it">
<head>
  <meta charset="utf-8">
  <title>Laboratorio Node.js</title>
</head>
<body>
  <h1>Come ti chiami?</h1>
  <form action="/saluto" method="post">
    <label>Nome: <input name="nome" required></label>
    <button type="submit">Invia</button>
  </form>
</body>
</html>`);
    return;
  }

  if (req.method === 'POST' && req.url === '/saluto') {
    const type = (req.headers['content-type'] || '').split(';')[0];
    if (type !== 'application/x-www-form-urlencoded') {
      res.writeHead(415, { 'Content-Type': 'text/plain; charset=utf-8' });
      res.end('Invia i dati con un normale form HTML.');
      return;
    }

    let body = '';
    req.setEncoding('utf8');
    req.on('data', (chunk) => {
      body += chunk;
    });
    req.on('end', () => {
      const dati = new URLSearchParams(body);
      const nome = (dati.get('nome') || '').trim();
      if (nome === '') {
        res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
        res.end('Scrivi un nome.');
        return;
      }
      res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
      res.end('Ciao, ' + nome + '!');
    });
    return;
  }

  if (req.url === '/saluto') {
    res.writeHead(405, { 'Allow': 'POST' });
    res.end('Usa POST per inviare il nome.');
    return;
  }

  if (req.url === '/') {
    res.writeHead(405, { 'Allow': 'GET' });
    res.end('Usa GET per la home.');
    return;
  }

  res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('Pagina non trovata.');
});

server.listen(PORT, IP, () => {
  console.log('Server attivo su http://' + IP + ':' + PORT);
});

Il corpo può arrivare in più pezzi: l’evento data porta un pezzo, end dice che è arrivato tutto. Per questo non leggiamo il nome subito fuori da end. URLSearchParams interpreta i campi e decodifica +, accenti e caratteri speciali. La risposta è testo semplice, quindi il nome non viene interpretato come HTML.

Prova nel secondo terminale

curl.exe -i --data-urlencode "nome=Ada Lovelace" http://127.0.0.1:3000/saluto
curl.exe -i -d "nome=" http://127.0.0.1:3000/saluto

Risultato atteso. Il form e il primo comando rispondono 200 con “Ciao, Ada Lovelace!”. Il campo vuoto dà 400. required aiuta il browser, ma il server deve comunque controllare i dati: curl può inviare un campo vuoto. Un formato diverso dal form dà 415.

Tocca a te. Aggiungi al form un input name="classe" e leggilo con dati.get. Prima controlla nel terminale quale corpo viene inviato, poi modifica la risposta.

TAPPA 3

PUT semplice: sostituire tutta la nota

Un esempio indipendente, senza POST. Il server parte con una nota in memoria. GET la legge, PUT ne sostituisce l’intero testo. Non aggiunge un pezzo e non crea una seconda nota. Ripetere lo stesso PUT lascia lo stesso contenuto.

server.cjs · soltanto GET e PUT sulla nota

const http = require('node:http');

const IP = '127.0.0.1';
const PORT = 3000;

let nota = 'Prima nota';

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/nota') {
    res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
    res.end(nota);
    return;
  }

  if (req.method === 'PUT' && req.url === '/nota') {
    if ((req.headers['content-type'] || '').split(';')[0] !== 'text/plain') {
      res.writeHead(415);
      res.end('Invia testo semplice.');
      return;
    }
    let body = '';
    req.setEncoding('utf8');
    req.on('data', (chunk) => { body += chunk; });
    req.on('end', () => {
      if (body.trim() === '') {
        res.writeHead(400);
        res.end('La nota non puo essere vuota.');
        return;
      }
      nota = body;
      res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
      res.end(nota);
    });
    return;
  }

  if (req.url === '/nota') {
    res.writeHead(405, { 'Allow': 'GET, PUT' });
    res.end('Usa GET oppure PUT.');
    return;
  }

  res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('Pagina non trovata.');
});

server.listen(PORT, IP, () => {
  console.log(`Server attivo su http://${IP}:${PORT}`);
});

Prova nel secondo terminale

curl.exe -i http://127.0.0.1:3000/nota
curl.exe -i -X PUT -H "Content-Type: text/plain" --data "Seconda nota" http://127.0.0.1:3000/nota
curl.exe -i http://127.0.0.1:3000/nota

Risultato atteso. Leggi “Prima nota”, sostituiscila, poi GET restituisce “Seconda nota”. Riavviando Node torna “Prima nota”: qui non stiamo salvando su disco.

I normali form HTML inviano GET o POST, non PUT o DELETE. Non usiamo una rotta GET /elimina per fingere una cancellazione. Ora proviamo questi metodi con curl; il frontend con fetch arriva solo nelle ultime tappe.

Tocca a te. Invia lo stesso PUT due volte, poi leggi. Prova un corpo vuoto: il server restituisce 400 e conserva la nota precedente.

TAPPA 4

DELETE semplice: eliminare la nota

Altro esempio indipendente. Partiamo di nuovo da “Prima nota”. DELETE imposta la variabile a null; GET risponde 404 quando non esiste più. Non occorre un corpo nella richiesta DELETE di questo esempio.

server.cjs · soltanto GET e DELETE

const http = require('node:http');

const IP = '127.0.0.1';
const PORT = 3000;

let nota = 'Prima nota';

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/nota') {
    if (nota === null) {
      res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
      res.end('La nota non esiste.');
      return;
    }
    res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
    res.end(nota);
    return;
  }

  if (req.method === 'DELETE' && req.url === '/nota') {
    nota = null;
    res.writeHead(204);
    res.end(); // Una risposta 204 non deve avere un corpo.
    return;
  }

  if (req.url === '/nota') {
    res.writeHead(405, { 'Allow': 'GET, DELETE' });
    res.end('Usa GET oppure DELETE.');
    return;
  }

  res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('Pagina non trovata.');
});

server.listen(PORT, IP, () => {
  console.log(`Server attivo su http://${IP}:${PORT}`);
});

Prova nel secondo terminale

curl.exe -i http://127.0.0.1:3000/nota
curl.exe -i -X DELETE http://127.0.0.1:3000/nota
curl.exe -i http://127.0.0.1:3000/nota
curl.exe -i -X DELETE http://127.0.0.1:3000/nota

Risultato atteso. Nell’ordine: 200 con la nota; 204 senza corpo; 404; ancora 204. Abbiamo scelto che eliminare una nota già assente sia comunque un successo senza corpo. Ripetere DELETE lascia lo stesso stato finale: la nota è assente.

Tocca a te. Controlla con -i che dopo 204 non venga inviato un messaggio. Poi riavvia: la nota iniziale ricompare perché lo stato era soltanto in memoria.

TAPPA 5

Un piccolo passo in più: unire i quattro metodi

Solo dopo le prove separate, uniamo i pezzi. Ora la nota inizialmente non esiste. POST /note la crea, GET /nota la legge, PUT /nota la sostituisce e DELETE /nota la elimina. Il corpo di POST e PUT qui è testo semplice, non il formato del form della tappa 2.

RichiestaEffettoRisposta
POST /noteCrea la nota se manca201 e Location: /nota; 409 se esiste
GET /notaLegge la nota200 oppure 404
PUT /notaSostituisce tutta la nota esistente200 oppure 404
DELETE /notaRende la nota assente204 senza corpo
GET /api/infoLegge informazioni sul laboratorio200 JSON

server.cjs · metodi riuniti

const http = require('node:http');

const IP = '127.0.0.1';
const PORT = 3000;

let nota = null;

// La callback riceve il testo completo soltanto dopo l'evento end.
function leggiCorpo(req, callback) {
  let body = '';
  req.setEncoding('utf8');
  req.on('data', (chunk) => { body += chunk; });
  req.on('end', () => { callback(body); });
}

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/nota') {
    if (nota === null) {
      res.writeHead(404);
      res.end('La nota non esiste.');
      return;
    }
    res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
    res.end(nota);
    return;
  }

  if (req.method === 'GET' && req.url === '/api/info') {
    res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
    res.end(JSON.stringify({ corso: 'Node.js', laboratorio: 2 }));
    return;
  }

  if ((req.method === 'POST' && req.url === '/note') ||
      (req.method === 'PUT' && req.url === '/nota')) {
    if ((req.headers['content-type'] || '').split(';')[0] !== 'text/plain') {
      res.writeHead(415);
      res.end('Invia Content-Type: text/plain.');
      return;
    }
    leggiCorpo(req, (body) => {
      if (body.trim() === '') {
        res.writeHead(400);
        res.end('Scrivi il testo della nota.');
        return;
      }
      if (req.method === 'POST' && nota !== null) {
        res.writeHead(409);
        res.end('La nota esiste gia. Usa PUT per sostituirla.');
        return;
      }
      if (req.method === 'PUT' && nota === null) {
        res.writeHead(404);
        res.end('Prima crea la nota con POST.');
        return;
      }
      nota = body;
      if (req.method === 'POST') {
        res.writeHead(201, { 'Content-Type': 'text/plain; charset=utf-8', 'Location': '/nota' });
      } else {
        res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
      }
      res.end(nota);
    });
    return;
  }

  if (req.method === 'DELETE' && req.url === '/nota') {
    nota = null;
    res.writeHead(204);
    res.end();
    return;
  }

  if (req.url === '/nota' || req.url === '/note' || req.url === '/api/info') {
    const allowed = req.url === '/nota' ? 'GET, PUT, DELETE' : req.url === '/note' ? 'POST' : 'GET';
    res.writeHead(405, { 'Allow': allowed });
    res.end('Metodo non consentito per questa rotta.');
    return;
  }

  res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('Pagina non trovata.');
});

server.listen(PORT, IP, () => {
  console.log(`Server attivo su http://${IP}:${PORT}`);
});

leggiCorpo raccoglie la logica data/end in una funzione: la callback riceve il testo quando è completo. Lo stato nota è condiviso tra le richieste di questo server, fino al riavvio. È un esempio locale con piccoli testi, senza database o utenti.

Prova nel secondo terminale

curl.exe -i http://127.0.0.1:3000/nota
curl.exe -i -H "Content-Type: text/plain" --data "Prima nota" http://127.0.0.1:3000/note
curl.exe -i -H "Content-Type: text/plain" --data "Duplicata" http://127.0.0.1:3000/note
curl.exe -i -X PUT -H "Content-Type: text/plain" --data "Nota aggiornata" http://127.0.0.1:3000/nota
curl.exe -i -X DELETE http://127.0.0.1:3000/nota
curl.exe -i http://127.0.0.1:3000/nota

Risultato atteso. Nell’ordine: 404, 201, 409, 200, 204, 404. Se PUT arriva prima della creazione risponde 404; un testo vuoto dà 400; un Content-Type diverso da text/plain dà 415.

Tocca a te. Prepara una tabella con stato della nota prima e dopo ogni comando. Spiega perché POST e PUT non sono intercambiabili in questo progetto.

TAPPA 6

Fetch, primo esempio: leggere testo e JSON

Da qui introduciamo JavaScript nel browser. Una richiesta fetch legge una risposta e permette di aggiornare la pagina senza navigare. Il server continua a fare le operazioni provate con curl.

Crea public/index.html con questo HTML senza CSS. Il server completo qui sotto aggiunge solo la rotta GET / per leggere quel file; gli altri metodi restano quelli della tappa 5.

server.cjs · serve anche il frontend

const http = require('node:http');
const fs = require('node:fs');
const path = require('node:path');

const IP = '127.0.0.1';
const PORT = 3000;

let nota = null;

// La callback riceve il testo completo soltanto dopo l'evento end.
function leggiCorpo(req, callback) {
  let body = '';
  req.setEncoding('utf8');
  req.on('data', (chunk) => { body += chunk; });
  req.on('end', () => { callback(body); });
}

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/') {
    fs.readFile(path.join(__dirname, 'public', 'index.html'), (error, content) => {
      if (error) {
        res.writeHead(500);
        res.end('Non riesco a leggere public/index.html.');
        return;
      }
      res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
      res.end(content);
    });
    return;
  }

  if (req.url === '/') {
    res.writeHead(405, { 'Allow': 'GET' });
    res.end('Usa GET per la home.');
    return;
  }

  if (req.method === 'GET' && req.url === '/nota') {
    if (nota === null) {
      res.writeHead(404);
      res.end('La nota non esiste.');
      return;
    }
    res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
    res.end(nota);
    return;
  }

  if (req.method === 'GET' && req.url === '/api/info') {
    res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
    res.end(JSON.stringify({ corso: 'Node.js', laboratorio: 2 }));
    return;
  }

  if ((req.method === 'POST' && req.url === '/note') ||
      (req.method === 'PUT' && req.url === '/nota')) {
    if ((req.headers['content-type'] || '').split(';')[0] !== 'text/plain') {
      res.writeHead(415);
      res.end('Invia Content-Type: text/plain.');
      return;
    }
    leggiCorpo(req, (body) => {
      if (body.trim() === '') {
        res.writeHead(400);
        res.end('Scrivi il testo della nota.');
        return;
      }
      if (req.method === 'POST' && nota !== null) {
        res.writeHead(409);
        res.end('La nota esiste gia. Usa PUT per sostituirla.');
        return;
      }
      if (req.method === 'PUT' && nota === null) {
        res.writeHead(404);
        res.end('Prima crea la nota con POST.');
        return;
      }
      nota = body;
      if (req.method === 'POST') {
        res.writeHead(201, { 'Content-Type': 'text/plain; charset=utf-8', 'Location': '/nota' });
      } else {
        res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
      }
      res.end(nota);
    });
    return;
  }

  if (req.method === 'DELETE' && req.url === '/nota') {
    nota = null;
    res.writeHead(204);
    res.end();
    return;
  }

  if (req.url === '/nota' || req.url === '/note' || req.url === '/api/info') {
    const allowed = req.url === '/nota' ? 'GET, PUT, DELETE' : req.url === '/note' ? 'POST' : 'GET';
    res.writeHead(405, { 'Allow': allowed });
    res.end('Metodo non consentito per questa rotta.');
    return;
  }

  res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('Pagina non trovata.');
});

server.listen(PORT, IP, () => {
  console.log(`Server attivo su http://${IP}:${PORT}`);
});

public/index.html · due letture minime

<!doctype html>
<html lang="it">
<head>
  <meta charset="utf-8">
  <title>Laboratorio Node.js</title>
</head>
<body>
  <h1>Leggi dal server senza cambiare pagina</h1>
  <button onclick="leggiNota()">Leggi la nota</button>
  <button onclick="leggiInfo()">Leggi il JSON</button>
  <pre id="risultato">Premi un pulsante.</pre>
  <script>
    const risultato = document.getElementById('risultato');

    function leggiNota() {
      fetch('/nota')
        .then((risposta) => risposta.text())
        .then((testo) => { risultato.textContent = testo; })
        .catch(() => { risultato.textContent = 'Errore di rete'; });
    }

    function leggiInfo() {
      fetch('/api/info')
        .then((risposta) => risposta.json())
        .then((dati) => { risultato.textContent = dati.corso; })
        .catch(() => { risultato.textContent = 'Errore di rete'; });
    }
  </script>
</body>
</html>

.then esegue il passo successivo quando l’operazione è pronta: prima arriva la risposta, poi ne leggiamo il corpo. Per il testo usiamo text(), per il JSON json(). Il catch gestisce errori di rete o lettura; un HTTP 404 da solo non fa fallire fetch.

Risultato atteso. Apri /: “Leggi la nota” mostra inizialmente il messaggio di assenza, mentre “Leggi il JSON” mostra Node.js. Crea una nota con il comando POST della tappa 5 e ripremi “Leggi la nota”: il testo appare senza cambiare URL. Una risposta 404 viene letta come testo; controlleremo lo status nella prossima tappa.

Tocca a te. Confronta il link del primo laboratorio con questi pulsanti: in quale caso cambia pagina? Quale codice viene eseguito nel browser e quale in Node?

TAPPA 7

Fetch, secondo esempio: quattro pulsanti essenziali

Mantieni server.cjs della tappa 6. Sostituisci solo public/index.html con questo frontend: un campo, quattro pulsanti e un risultato. Nessun CSS, nessuna libreria.

public/index.html · GET, POST, PUT e DELETE

<!doctype html>
<html lang="it">
<head>
  <meta charset="utf-8">
  <title>Laboratorio Node.js</title>
</head>
<body>
  <h1>Una nota</h1>
  <label>Testo: <input id="testo"></label>
  <p>
    <button onclick="invia('GET')">Leggi</button>
    <button onclick="invia('POST')">Crea</button>
    <button onclick="invia('PUT')">Sostituisci</button>
    <button onclick="invia('DELETE')">Elimina</button>
  </p>
  <pre id="risultato">Premi un pulsante.</pre>
  <script>
    async function invia(metodo) {
      const risultato = document.getElementById('risultato');
      const rotta = metodo === 'POST' ? '/note' : '/nota';
      const opzioni = { method: metodo };

      if (metodo === 'POST' || metodo === 'PUT') {
        opzioni.headers = { 'Content-Type': 'text/plain' };
        opzioni.body = document.getElementById('testo').value;
      }

      try {
        const risposta = await fetch(rotta, opzioni);
        const testo = await risposta.text();
        risultato.textContent = 'Stato ' + risposta.status + ': ' + testo;
      } catch (error) {
        risultato.textContent = 'Errore di rete: ' + error.message;
      }
    }
  </script>
</body>
</html>

Qui usiamo async/await come un secondo modo di attendere la risposta. async abilita await nella funzione; await fetch aspetta la risposta e await risposta.text() aspetta il corpo. Per GET e DELETE non impostiamo body. Lo status viene mostrato anche quando è 400 o 404: non lo confondiamo con un errore di rete.

Risultato atteso. Dopo un riavvio: Leggi → 404; scrivi un testo e premi Crea → 201; Crea di nuovo → 409; cambia testo e premi Sostituisci → 200; Leggi mostra il nuovo testo; Elimina → 204 senza corpo; Leggi → 404. Se premi Crea con campo vuoto ottieni 400. Ripeti i clic uno alla volta, aspettando il risultato.

Tocca a te. Ferma Node mantenendo la pagina già aperta: il successivo clic mostra un errore di rete. Riavvia e ripeti la sequenza. In Network confronta i quattro metodi e i corpi inviati.

Prima di continuare

Ripeti una creazione, una lettura, una sostituzione e una cancellazione. Devi saper distinguere un form che naviga, una richiesta fetch che aggiorna un elemento e lo stato che rimane soltanto nella memoria di Node.

Passa poi a Laboratorio 03 · Express essenziale, dove riscriviamo pochi esempi già conosciuti.

Al termine ferma il server con Ctrl + C. Se vedi EADDRINUSE, la porta è già occupata: ferma la tua versione precedente prima di avviarne un’altra. Salva il lavoro prima di sostituire i file con la versione della tappa successiva.

Riferimenti: Node HTTP e corpo della richiesta, form HTML, PUT, DELETE, Fetch.

Le fonti e i riferimenti sono indicati nelle introduzioni ai percorsi e nei singoli materiali.