【问题标题】:why is 'body' empty in nodejs express post request?为什么nodejs express post请求中的“body”为空?
【发布时间】:2021-08-21 12:01:00
【问题描述】:

我正在尝试捕获 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" })
  }
})

【问题讨论】:

  • 我们需要一些代码
  • @AndreyPopov 已更新...
  • 这是你的路由器。您需要展示您的服务器是如何设置的,以及您如何发送您的请求...
  • 它在主javascript文件(app.js)中,在路由器代码之前使用。
  • 如果您没有设置 headers ,使用 Postman 来测试带有 JSON 数据的 HTTP post 操作,选择 raw 选项并设置以下 header 参数Content-Type: application/json

标签: node.js json express request postman


【解决方案1】:

在你的标题中更正这个:

content-type: application/json

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-06-26
      • 2019-02-25
      • 2018-04-30
      • 1970-01-01
      • 2016-10-14
      • 2018-06-16
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      相关资源
      最近更新 更多