req.body 在 express 应用程序的 post 路由中未定义

And*_*ady 3 javascript node.js express

这是我的路由器

router.post('/', async(req, res) => {

const posts = await loadPostsCollection()

await posts.insertOne({
    text: req.body.text,
    createdAt: new Date()
})
res.status(201).send()
})
Run Code Online (Sandbox Code Playgroud)

这是终端错误

在端口 3090 上进行列表 ..... (node:7764) UnhandledPromiseRejectionWarning: TypeError: 无法读取 /Users/macbook/Desktop/node-project/server/routes/api/posts.js:19 处未定义的属性“文本”: 24 在 processTicksAndRejections (internal/process/task_queues.js:94:5) (node:7764) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个错误要么是因为在没有 catch 块的情况下抛出了异步函数,要么是因为拒绝了一个没有用 .catch() 处理过的承诺。(rejection id: 1) (node:7764) [DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的承诺拒绝将使用非零退出代码终止 Node.js 进程。

Ram*_*jan 5

这是因为您req.body将产生价值undefined。因此,当您尝试这样做时,req.body.text您会在尝试访问text某个undefined值的属性时遇到错误。

你得到的原因undefined是你的 express 应用程序无法解析请求正文。

为此,您需要安装body-parser中间件依赖项,

npm i body-parser

然后将此中间件添加到您的快递应用程序中,

const bodyParser = require('body-parser')
app.use(bodyParser.json())
Run Code Online (Sandbox Code Playgroud)

参考:https : //expressjs.com/en/resources/middleware/body-parser.html

这是一个示例应用程序,

const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())

app.post('/', (req, res) => {
    return res.send(`Hello ${req.body.name}!`)
})

app.listen(3000, () =>
    console.log(`Example app listening at http://localhost:${port}`)
)

Run Code Online (Sandbox Code Playgroud)

现在,如果您使用 curl 调用上面的示例应用程序,

curl -XPOST localhost:3000 -H "Content-Type: application/json" -d '{"name":"Ram"}'
Run Code Online (Sandbox Code Playgroud)

你会得到回复“Hello Ram!”