Getting info from the request

suggest change

req is the request object in a route handler. For the route /settings/:user_id and the request /settings/32135?field=name:

// get the full path
req.originalUrl // => /settings/32135?field=name

// get the user_id param
req.params.user_id // => 32135     

// get the query value of the field
req.query.field // => 'name'

Request headers are available the same way:

req.get('Content-Type')
// "text/plain"

Other fields need middleware. body-parser turns the raw body into an object. Express 4.16 and later also provides express.json() and express.urlencoded(), which cover the same two cases.

var app = require('express')();
var bodyParser = require('body-parser');

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

For a request like this:

PUT /settings/32135
{
  "name": "Peter"
}

the posted name is:

req.body.name
// "Peter"

Cookies need middleware such as cookie-parser:

req.cookies.name

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents