Introduction
In this blog article, we shall learn how to handle POST requests in an Express application.
POST HTTP request uses the POST method and is mostly used when sending some data along with the request to the HTTP server.
In Express you’ll need to enable a middleware to parse the body of Content-type: application/json
. This enables parsing incoming JSON content inside the body of the incoming request.
Values sent in the POST request are populated inside the req.body
object.
A Simple Express application
Let’s setup a simple Express application
const express = require('express')
const app = express()
// enable middleware to parse body of content-type: application/json
app.use(express.json())
app.post('/', (req, res) => {
// get request values inside req.body
const price = req.body.price
const orderId = req.body.orderId
// use price, orderId to do something meaningful
})
Requests are client constructed values and should be sanitized and validated before use once they get to the Express application.
Summary
To handle POST requests in Express, we need to enable parsing of JSON by enabling the json middleware for the express application.
Found this article helpful? You may follow me on Twitter @nkmurgor where I tweet about interesting topics on web development.