why is 'body' empty in nodejs express post request?

Viewed 701

I'm trying to catch raw data in the body that's sent by Postman. This is the raw data:

{
    "hello": "world"
}

I'm using app.use(express.json()) in the server. When I send the post request I just get an empty JSON. Why is this happening?

App.js code:

import express from "express"
import { connectDb } from "./connectDb.js"
import create from "./routes/create.js" // router

const app = express()
app.use(express.json())

connectDb()

const PORT = process.env.PORT || 5000

app.use("/api", create)

app.listen(PORT, () => console.log(PORT, "Connected..."))

Router Code:

import express from "express"
import Game from "../models/gamesModel.js" // mongoose model
const router = express.Router()

router.route("/create/game").post(async (req, res) => {
  console.log(req.body)
  try {
    const game = await Game.create(req.body)
    res.json(game)
  } catch (error) {
    res.json({ message: "Invalid Information" })
  }
})
2 Answers

As you are using POSTMAN to be able to access request body via req.body when you are using the buildin express.json middleware you will have to ensure that are send the request Body using RAW type and set the type of the body as JSON like in the image shown bellow

enter image description here

If the body type is set to something else (Text, JavScript, HTML, XML) You'll still getting an empty body. Only when it's set as JSON you will get req.body filled with data which you sent as part of you request body

correct this in your headers:

content-type: application/json
Related