What are "res" and "req" parameters in Express functions?
In the following Express function:
app.get('/user/:id', function(req, res){
res.send('user' + req.params.id);
});
What are req
and res
? What do they stand for, what do they mean, and what do they do?
Thanks!
req
is an object containing information about the HTTP request that raised the event. In response to req
, you use res
to send back the desired HTTP response.
Those parameters can be named anything. You could change that code to this if it's more clear:
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
Edit:
Say you have this method:
app.get('/people.json', function(request, response) { });
The request will be an object with properties like these (just to name a few):
-
request.url
, which will be"/people.json"
when this particular action is triggered -
request.method
, which will be"GET"
in this case, hence theapp.get()
call. - An array of HTTP headers in
request.headers
, containing items likerequest.headers.accept
, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc. - An array of query string parameters if there were any, in
request.query
(e.g./people.json?foo=bar
would result inrequest.query.foo
containing the string"bar"
).
To respond to that request, you use the response object to build your response. To expand on the people.json
example:
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);
});
I noticed one error in Dave Ward's answer (perhaps a recent change?):
The query string paramaters are in request.query
, not request.params
. (See https://stackoverflow.com/a/6913287/166530 )
request.params
by default is filled with the value of any "component matches" in routes, i.e.
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
and, if you have configured express to use its bodyparser (app.use(express.bodyParser());
) also with POST'ed formdata. (See How to retrieve POST query parameters? )
Request and response.
To understand the req
, try out console.log(req);
.