首页 > 解决方案 > express.js req.body 在中间件中未定义

问题描述

我目前在我的节点应用程序中遇到问题。

尝试在发布请求中使用中间件时, req.body 变得未定义。

例如;

router.post('/newpost', ensureAuthenticated, createPost, upload.single('file'), async (req, res) =>{
    console.log(req.body);
}

async function createPost(req, res, next){
    console.log(req.body);
    next();
}

当 createPost 函数运行时,它会将 req.body 记录为未定义。但是当 req.body 被记录在 router.post 中时,它就被定义了。

是我想念的东西吗?或者这只是不可能的。

我还确保我已经包含了 bodyparser 并在我的路线之前对其进行了初始化。

标签: javascriptnode.jsexpress

解决方案


好吧,我刚刚测试过,一切正常,在评论中有我的建议

这是我的测试内容:

我的index.js

const express = require('express')

const router = express.Router()
const app = express()
const PORT = process.env.PORT || 3002

app.use(express.json())

const createPost = (req, res, next) => {
    console.log('createPost', req.body)
    next()
}

router.post('/newpost', createPost, (req, res) => {
    console.log('/nextpost', req.body)
    res.json({ message: 'ok' })
})

app.use('/', router)

app.listen(PORT, () => {
    console.log(
        `server ready at http://localhost:${PORT}`
    )
})

和一个简单的REST 客户端文件

@HOST = http://localhost:3002

POST {{HOST}}/newpost
Content-Type: application/json

{
    "fname": "Bruno",
    "lname": "Alexandre",
    "nick": "balexandre"
}

结果是

❯ node .\index.js
server ready at http://localhost:3002
createPost { fname: 'Bruno', lname: 'Alexandre', nick: 'balexandre' }
/nextpost { fname: 'Bruno', lname: 'Alexandre', nick: 'balexandre' }

和电话的响应

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 16
ETag: W/"10-/VnJyQBB0+b7i4NY83P42KKVWsM"
Date: Tue, 26 Jan 2021 19:59:21 GMT
Connection: close

{
  "message": "ok"
}

截图(点击查看完整图片)

在此处输入图像描述


警告

确保您正在传递Content-Type: application/json您的POST请求,请记住您告诉 Express 您希望将正文解析为,.json()因此请确保它知道您将 json 作为请求正文传递

更多信息...req.bodyundefined当我不使用解析器时,例如:

在此处输入图像描述


添加

具有工作解决方案的 GitHub 存储库 > https://github.com/balexandre/so65907925


推荐阅读