Cosa sono i “res” e parametri “REQ” nelle funzioni Express?
Domanda
Nel seguente funzione espresso:
app.get('/user/:id', function(req, res){
res.send('user' + req.params.id);
});
Quali sono req
e res
? Che cosa significano, che cosa significano e cosa fanno?
Grazie!
Soluzione
req
è un oggetto che contiene informazioni sulla richiesta HTTP che ha generato l'evento. In risposta a req
, si utilizza res
rispedire la risposta HTTP desiderato.
Questi parametri possono essere chiamato in qualsiasi modo. Si potrebbe cambiare la situazione codice a questo se è più chiaro:
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
Modifica:
dire che hai 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 viene attivato questo particolare azione -
request.method
, che sarà"GET"
in questo caso, quindi, la chiamataapp.get()
. - Una serie di intestazioni HTTP in
request.headers
, contenente oggetti comerequest.headers.accept
, che è possibile utilizzare per determinare quale tipo di browser che ha effettuato la richiesta, che tipo di risposte in grado di gestire, anche se non è in grado di comprendere la compressione HTTP, etc. - Un array di parametri stringa query se c'erano, in
request.query
(ad esempio/people.json?foo=bar
comporterebberequest.query.foo
contenente la"bar"
stringa).
Per rispondere a tale richiesta, è possibile utilizzare l'oggetto Response per costruire la vostra 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 data is fetched 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);
});
Altri suggerimenti
Ho notato un errore nella risposta di Dave Ward (forse un recente cambiamento?):
I paramaters stringa di query sono in request.query
, non request.params
. (Vedere https://stackoverflow.com/a/6913287/166530 )
request.params
per default viene riempito con il valore dei "componenti" partite in percorsi, cioè.
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
e, se si è configurato espressamente di utilizzare il suo bodyparser (app.use(express.bodyParser());
) anche con POST'ed formdata. (Vedere Come recuperare POST parametri di query? )
Richiesta e risposta.
Per capire il req
, provare console.log(req);
.