Gestione dei dati delle richieste: body, query e parametri
Imparate come Express riceve e analizza i dati in arrivo dai client, inclusi i parametri delle route, le stringhe di query, i body JSON e gli invii di moduli.
Gestione dei dati delle richieste: body, query e parametri è una lezione Node.js Backend Development Bootcamp gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Node.js Backend Development Bootcamp, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Node.js Backend Development Bootcamp include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Where Client Data Comes From
An HTTP request can carry data in several places. An Express handler reads each from a different property of the req object:
- Route params:
req.params - Query string:
req.query - Request body:
req.body - Headers:
req.headers
app.get('/info', (req, res) => {
res.json({ params: req.params, query: req.query });
});Route Parameters
Route parameters are named URL segments prefixed with a colon. For /users/:id, a request to /users/42 gives req.params.id === '42'.
They are always strings, so convert to numbers when needed.
app.get('/users/:id', (req, res) => {
const id = Number(req.params.id);
res.send('Looking up user ' + id);
});Multiple Route Parameters
A route can capture several params at once. Each colon segment becomes a key on req.params.
app.get('/books/:author/:title', (req, res) => {
const { author, title } = req.params;
res.send(author + ' wrote ' + title);
});Query Strings
Everything after the ? in a URL is the query string. Express parses it into req.query as key-value pairs.
For /search?term=node&page=2, you get req.query.term and req.query.page.
app.get('/search', (req, res) => {
const { term, page } = req.query;
res.send('Searching ' + term + ' page ' + (page || 1));
});Parsing JSON Bodies
POST and PUT requests usually send a JSON body. Express does not parse it by default — you must enable the built-in middleware express.json().
const express = require('express');
const app = express();
app.use(express.json());
app.post('/users', (req, res) => {
res.json({ received: req.body });
});Parsing Form Data
HTML forms submit data as application/x-www-form-urlencoded. Enable express.urlencoded() to populate req.body from form fields.
app.use(express.urlencoded({ extended: true }));
app.post('/login', (req, res) => {
res.send('Welcome ' + req.body.username);
});Validating Required Fields
Never trust client input. Always check that required fields are present before using them, and respond with a 400 Bad Request if something is missing.
app.post('/users', (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({ error: 'name and email required' });
}
res.status(201).json({ name, email });
});Reading Headers
Headers carry metadata like authentication tokens and content types. Access them via req.headers (keys are lowercased) or the helper req.get().
app.get('/secure', (req, res) => {
const auth = req.get('Authorization');
res.send('Token: ' + (auth || 'none'));
});Default Values for Optional Data
Query and body values are often optional. Provide sensible defaults so your handler does not break when a parameter is omitted.
app.get('/products', (req, res) => {
const page = Number(req.query.page) || 1;
const limit = Number(req.query.limit) || 10;
res.json({ page, limit });
});Combining All Three Sources
A single endpoint can read params, query, and body together. For example, updating a resource identified by a param, with options in the query, and new data in the body.
app.put('/users/:id', (req, res) => {
const id = req.params.id;
const notify = req.query.notify === 'true';
const updates = req.body;
res.json({ id, notify, updates });
});Common Mistakes
Watch out for these pitfalls:
- Forgetting
express.json()soreq.bodyisundefined - Treating params as numbers without converting
- Trusting input without validation
- Confusing query (
?key=value) with params (/:key)
Quick Check
Test your knowledge of Express request data.
Recap
You now know how Express receives client data:
req.paramsfor named URL segmentsreq.queryfor the query stringreq.bodyfor JSON (withexpress.json()) and forms (withexpress.urlencoded())req.headers/req.get()for metadata
Always validate and provide defaults — never trust raw client input.
Domande Frequenti
La lezione «Gestione dei dati delle richieste: body, query e parametri» è gratuita?
Sì — il testo completo di «Gestione dei dati delle richieste: body, query e parametri» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Node.js Backend Development Bootcamp, passa a CoddyKit PRO. Il corso Node.js Backend Development Bootcamp include 4 lezioni in totale.
Cosa imparerò in «Gestione dei dati delle richieste: body, query e parametri»?
Imparate come Express riceve e analizza i dati in arrivo dai client, inclusi i parametri delle route, le stringhe di query, i body JSON e gli invii di moduli. Eserciti Node.js Backend Development Bootcamp con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Node.js Backend Development Bootcamp?
Non è richiesta alcuna esperienza precedente. Node.js Backend Development Bootcamp su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Gestione dei dati delle richieste: body, query e parametri»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Node.js Backend Development Bootcamp?
Sì. Ogni lezione Node.js Backend Development Bootcamp include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Fondamenti del framework Express.js
- Routing e middleware in Express
- Progettare endpoint API RESTful
- Gestione dei dati delle richieste: body, query e parametri