Retrieve the POST query parameters using Express
By Flavio Copes
Learn how to retrieve POST request data in Express using the express.json() or express.urlencoded() middleware and reading the values from req.body.
To read POST data in Express, add the express.json() or express.urlencoded() middleware, then access the parsed values on req.body inside your route handler.
POST query parameters are sent by HTTP clients for example by forms, or when performing a POST request sending data.
Express does not parse the request body on its own. You register a middleware that matches the format the client used, and it fills req.body for you.
If the data was sent as JSON, using Content-Type: application/json, you will use the express.json() middleware:
const express = require('express')
const app = express()
app.use(express.json())
If the data was sent using Content-Type: application/x-www-form-urlencoded, which is what a plain HTML form uses by default, you will need to use the express.urlencoded() middleware:
const express = require('express')
const app = express()
app.use(express.urlencoded({
extended: true
}))
The extended: true option parses the body using the qs library, which supports nested objects. A form field named address[city] becomes req.body.address.city. With extended: false you get the simpler querystring parser, and that field stays a flat 'address[city]' key.
You can register both middlewares. Each one only acts when the Content-Type header matches its format.
Reading the values
In both cases you can access the data by referencing it from Request.body:
app.post('/form', (req, res) => {
const name = req.body.name
})
Here is a complete example. It accepts a signup form with a name and an email, and echoes them back:
const express = require('express')
const app = express()
app.use(express.json())
app.post('/signup', (req, res) => {
const { name, email } = req.body
res.send(`Welcome ${name}, we'll write you at ${email}`)
})
app.listen(3000)
You can test it with curl:
curl -X POST http://localhost:3000/signup \
-H 'Content-Type: application/json' \
-d '{"name": "Flavio", "email": "[email protected]"}'
What if req.body is undefined?
If req.body comes back undefined, the middleware didn’t run. Either you forgot to register it, or you registered it after the route, or the client sent a Content-Type that doesn’t match.
Register the middleware before the routes that need it, and check the header the client actually sends. A fetch() call, for example, does not send Content-Type: application/json unless you set it yourself.
Note: older Express versions required the use of the
body-parsermodule to process POST data. This is no longer the case as of Express 4.16 (released in September 2017) and later versions.