DEV Community

Cover image for How to handle POST Requests in Express
Naftali Murgor
Naftali Murgor

Posted on

How to handle POST Requests in Express

Introduction

In this blog article, we shall learn how to handle POST requests in Express.

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 in 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
})
Enter fullscreen mode Exit fullscreen mode

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.


Found this article helpful? You may follow my handle on twitter @nkmurgor where I tweet about interesting topics on web development.

Discussion (0)