Express, request parameters

Convenient reference to all request object properties and how to use them

Request parameter

I mentioned how the Request object saves all HTTP request information.

These are the main attributes you might use:

property description
. application Have a reference to the Express application object
.baseUrl The basic path of the application response
. body Include the submitted data in the request body (it must be manually analyzed and populated before it can be accessed)
. Biscuit Contains the requested cookie (requiredcookie-parserMiddleware)
. CPU name Hostname, such asHost HTTP headervalue
.ip Client IP
. method HTTP method used
.params Route named parameters
. Path URL path
. protocol Request agreement
. ask An object containing all query strings used in the request
. safe True if the request is secure (using HTTPS)
.signedCookies Contains the signed cookie sent by the request (requirescookie-parserMiddleware)
.xhr If the request isXMLHttpRequest

How to retrieve GET query string parameters using Express

The query string is the part after the URL path and starts with a question mark?.

example:

?name=flavio

You can add multiple query parameters in the following ways&:

?name=flavio&age=35

How to get those query string values in Express?

Express by fillingRequest.queryFor our object:

const express = require('express')
const app = express()

app.get(’/’, (req, res) => { console.log(req.query) })

app.listen(8080)

The object is populated by the attributes of each query parameter.

If there are no query parameters, it is an empty object.

This makes it easy to iterate using a for...in loop:

for (const key in req.query) {
  console.log(key, req.query[key])
}

This will print the query attribute key and value.

You can also access individual properties:

req.query.name //flavio
req.query.age //35

How to use Express to retrieve POST query string parameters

POST query parameters are sent by the HTTP client (for example, via a form) or when sending data when performing a POST request.

How do you access this data?

If the data is sent asJSON format, UseContent-Type: application/json, You will useexpress.json()Middleware:

const express = require('express')
const app = express()

app.use(express.json())

If the data is sent byContent-Type: application/x-www-form-urlencoded, You need to useexpress.urlencoded()Middleware:

const express = require('express')
const app = express()

app.use(express.urlencoded({ extended: true }))

In both cases, you can access the data by referencing the data in the following ways:Request.body:

app.post('/form', (req, res) => {
  const name = req.body.name
})

Note: Earlier Express version needs to be usedbody-parserModule for processing POST data. This is no longer the case with Express 4.16 (released in September 2017) and later.

Download mine for freeExpress.js manual


More crash tutorials: