为什么在 nodejs express post 请求中 'body' 为空?

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

我正在尝试捕获 Postman 发送的正文中的原始数据。这是原始数据:

{
    "hello": "world"
}

我在服务器中使用 app.use(express.json())。当我发送 post 请求时,我只得到一个空的 JSON。为什么会这样?

App.js代码:

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

路由器代码:

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

当您使用 POSTMAN 能够通过 req.body 访问请求正文时,当您使用内置 express.json 中间件时,您必须确保使用 [=12] 发送请求正文=] 输入并将正文类型设置为 JSON,如下图所示

如果正文类型设置为其他内容(文本、JavScript、HTML、XML),您仍然会得到一个空的正文。只有当它被设置为 JSON 时,你才会得到 req.body 填充你作为请求正文的一部分发送的数据

在您的 headers 中更正此问题:

content-type: application/json