javascript - 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 并在我的路线之前对其进行了初始化。
解决方案
好吧,我刚刚测试过,一切正常,在评论中有我的建议
这是我的测试内容:
我的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.body
仅undefined
当我不使用解析器时,例如:
添加
具有工作解决方案的 GitHub 存储库 > https://github.com/balexandre/so65907925
推荐阅读
- android - Gradle DSL 方法未找到:'exlude()' 可能的原因:
- c# - 服务器断开连接后,C# 程序卡在 FtpWebResponse 中
- c++ - 仅当项目不在列表中时如何将项目添加到列表中。如果数据未插入模型中,则警告用户
- c# - 无法隐式转换字典列表
ICollection 的类型参数 - c# - SerialPort.GetPortNames() 导致 ContextSwitchDeadlock 异常,为什么?
- c99 - 我是否正确阅读了 C99 语法?
- javascript - 从数据组件访问上传的文件
- javascript - 如何将数据从节点 js 发布到 codeigniter?
- java - @ApplicationPath 注解可以用在接口上吗?
- node.js - Docker容器在运行时抛出错误