ExpressJS req.body is empty JSON

Issue

When I hit my POST endpoint with JSON using Postman, my expressJS application wrongly claims that my JSON is an empty object.

Versions:

express: "4.17.1"
npm: ‘7.11.1’
node: ‘15.12.0’

Code:

index.js

const express = require( 'express' );
const app = express();
const controller = require ( './modules/controller' );
app.use( express.json() );
app.post( '/broken', ( req, res ) => controller.post( req, res ) );

controller.js

module.exports.post = async ( req, res ) =>
{
    const body = req.body;
    log.debug( `body received from request ${JSON.stringify( body )}` );
}

Postman config:

POST body (raw):

{
    "a":"b"
}

Headers:

Content-Type: application/json

Expected behaviour:

Logs out: body received from request {"a"="b"}

Actual behaviour:

Logs out: body received from request {}

Solution

Postman

Just wanna point out that the issue may come from Postman. When you create a new call on Postman the default body (raw) type it uses is "text". It needs to be set to JSON instead.

Answered By – Nick Gr

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published