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 triggeredrequest.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=barwould result inrequest.query.foocontaining 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);
});