req
è un oggetto contenente informazioni sulla richiesta HTTP che ha generato l'evento. In risposta a req
, si utilizza res
per inviare la risposta HTTP desiderata.
Questi parametri possono essere denominati qualsiasi cosa. Si potrebbe cambiare la situazione codice a questo se è più chiaro:
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
Edit:
Diciamo che avete questo metodo:
app.get('/people.json', function(request, response) { });
La richiesta sarà un oggetto con immobili come questi (solo per citarne alcuni):
request.url
, che sarà "/people.json"
quando questo partico l'azione lar è attivata
request.method
, che sarà "GET"
in questo caso, quindi la chiamata app.get()
.
- Una matrice di intestazioni HTTP in
request.headers
, contenente articoli come request.headers.accept
, che è possibile utilizzare per determinare quale tipo di browser ha effettuato la richiesta, quale tipo di risposte può gestire, indipendentemente dalla sua capacità di comprendere la compressione HTTP, ecc.
- Un array di parametri di stringa di query se ce ne fossero, in
request.params
(ad esempio /people.json?foo=bar
risulterebbe in request.params.foo
contenente la stringa "bar"
).
Per rispondere a tale richiesta, utilizzare l'oggetto risposta per creare la risposta. Per espandere sull'esempio people.json
:
app.get('/people.json', function(request, response) {
// We want to set the content-type header so that the browser understands
// the content of the response.
response.contentType('application/json');
// Normally, the would probably come from a database, but we can cheat:
var people = [
{ name: 'Dave', location: 'Atlanta' },
{ name: 'Santa Claus', location: 'North Pole' },
{ name: 'Man in the Moon', location: 'The Moon' }
];
// Since the request is for a JSON representation of the people, we
// should JSON serialize them. The built-in JSON.stringify() function
// does that.
var peopleJSON = JSON.stringify(people);
// Now, we can use the response object's send method to push that string
// of people JSON back to the browser in response to this request:
response.send(peopleJSON);
});
fonte
2011-01-14 21:48:11
Non capisco. Potresti mostrare un esempio di quale risposta può essere? E quale sarà il risultato? – expressnoob
puoi usare curl per vedere la risposta completa con le intestazioni – generalhenry
Aggiornamento della risposta con ulteriori spiegazioni. Ha più senso? –