What are "res" and "req" parameters in Express functions?
Asked Answered
F

3

217

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!

Forty answered 14/1, 2011 at 21:43 Comment(2)
req == "request" // res == "response"Marthmartha
I also wanted to add up my opinion, we should prefer to use params name as request/response instead of req/res as there is only character difference, which may become the cause of the bug, once our codebase increases. Thanks.Wanderjahr
W
321

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 the app.get() call.
  • An array of HTTP headers in request.headers, containing items like request.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 in request.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);
});
Wheelock answered 14/1, 2011 at 21:48 Comment(9)
you can use curl to see the response complete with headersRehash
You might want to check out: en.wikipedia.org/wiki/Hypertext_Transfer_Protocol. Not being snarky, that's something all of us who develop for the Web need to know about!Robinrobina
Yes this was great should be on main page of the express.js website.Debose
expressnoob - response is an object, just like the request object is, but it contains fields and methods pertaining to the response. Normally the response's send() method is used. send() accepts a whole bunch of different types for the first argument, which becomes the HTTP response body, and the second argument is the HTTP response code.Whig
If someone is looking for details of req and res structure, it is described in express docs: req:expressjs.com/en/api.html#req, res: expressjs.com/en/api.html#resHalfbound
OK, so the server ("app") has received a GET request for "/people.json". The request argument contains lots of useful details about that request, and the response argument allows you to choose what to send back in your reply. Neat. Thanks.Neu
When I console.log(request.params) it prints out undefinedIlltimed
@Debose The express.js.com website has some example response methods to illustrate this further.Marthmartha
Are req and res exclusive to expressjs or are these the NodeJs Request and Response objects?Bonnard
R
26

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://mcmap.net/q/45180/-how-to-get-get-query-string-variables-in-express-js-on-node-js )

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? )

Rosales answered 2/2, 2012 at 18:46 Comment(0)
R
7

Request and response.

To understand the req, try out console.log(req);.

Rehash answered 14/1, 2011 at 21:47 Comment(2)
This doesn't help; the output in the console is [object Object].Melisma
If you want json, you have to: console.log(JSON.Stringify(req.body);Glassblowing

© 2022 - 2024 — McMap. All rights reserved.