DEV Community

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

Posted on

14 2

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay