简体   繁体   中英

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

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" })
  }
})

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

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM