[英]why is 'body' empty in nodejs express post request?
I'm trying to catch raw data in the body that's sent by Postman.我正在尝试捕获 Postman 发送的正文中的原始数据。 This is the raw data:
这是原始数据:
{
"hello": "world"
}
I'm using app.use(express.json())
in the server.我在服务器中使用
app.use(express.json())
。 When I send the post request I just get an empty JSON.当我发送 post 请求时,我只得到一个空的 JSON。 Why is this happening?
为什么会这样?
App.js code: 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..."))
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当您使用 POSTMAN 以便在使用内置
express.json
中间件时能够通过req.body
访问请求正文时,您将必须确保使用RAW
类型发送请求正文并将正文的类型设置为JSON
如下图所示
If the body type is set to something else (Text, JavScript, HTML, XML) You'll still getting an empty body.如果正文类型设置为其他类型(文本、JavScript、HTML、XML),您仍然会得到一个空正文。 Only when it's set as
JSON
you will get req.body
filled with data which you sent as part of you request body只有当它设置为
JSON
时,您才会获得req.body
填充数据,这些数据是您作为请求正文的一部分发送的
correct this in your headers:在您的标题中更正这一点:
content-type: application/json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.