Request

Request

The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the object is always referred to as req (and the HTTP response is res) but its actual name is determined by the parameters to the callback function in which you’re working

For example:

app.js
app.get("/user/:id", (req, res) => {
  res.send(`user ${req.params.id}`);
});

But you could just as well have:

app.js
app.get("/user/:id", (request, response) => {
  response.send(`user ${request.params.id}`);
});

The req object is an enhanced version of Node’s own request object and supports all built-in fields and methods.

Properties

req.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.

app.js
const app = require("minimaal");
const bodyParser = require("body-parser");
const multer = require("multer"); // v1.0.5
const upload = multer(); // for parsing multipart/form-data
 
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
 
app.post("/profile", upload.array(), (req, res, next) => {
  console.log(req.body);
  res.json(req.body);
});

req.get

This method is useful for retrieving specific header values in a simplified manner, enhancing readability and ease of use when working with HTTP requests.

app.js
req.get("Host"); // Returns 'example.com'
req.get("User-Agent"); // Returns 'Mozilla/5.0'
req.get("Accept"); // Returns 'text/html'
req.get("Content-Type"); // Returns undefined if the 'Content-Type' header is not present

req.params

This property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /user/:name, then the “name” property is available as req.params.name. This object defaults to .

app.js
console.dir(req.params.name);