繁体   English   中英

express.js req.body 在中间件中未定义

[英]express.js req.body undefined in middleware

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

在尝试在发布请求中使用中间件时, 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 function 运行时,它会将 req.body 记录为未定义。 但是当 req.body 被记录在 router.post 中时,它就被定义了。

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

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

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

这是我的测试内容:

我的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"
}

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

在此处输入图像描述


警告

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

更多信息...... req.body仅在我不使用解析器时undefined ,例如:

在此处输入图像描述


添加

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM