Express.js + body-parser:POST请求中的空req.body
我正在使用Express和body-parser中间件来处理传入的请求。 在前端,我有一个表单,只是一个隐藏的input和一个提交button(写在帕格):
form(notes="saveNotesForm" action=`/lessons/${lesson._id}/notes` method="POST" enctype="application/x-www-form-urlencoded") input(type="hidden" id="hiddenNotes" name="hiddenNotes" alt="Notes Copy" value="test").notesHidden input(type="submit" name="saveNotes" alt="Save Notes" value="Save")
在后端,我有Express应用程序使用body-parser:
const bodyParser = require('body-parser'); // ... app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));
处理传入请求的路由:
router.post('/lessons/:lessonID/notes', lessonController.updateNotes); // ... and in lessonController: exports.updateNotes = async (req, res) => { console.log('updateNotes request received'); console.log(req.body); res.status(200).json({ status: 'success' }); }
当我尝试在req.body
中使用req.body
时,body是一个空对象,但是至less应该具有值为"test"
hiddenNotes
属性。 如果您有任何问题或者认为您发现问题,请发表评论!
[更新]
这是一个愚蠢的错误,我忘了我已经写了一个单独的事件处理程序,当这个表单被提交 – 它只是把我发布之前,我经历了我所有的代码:)事件处理程序使用axios ,看起来像这样:
const SaveNotesButton = $('form.saveNotes'); SaveNotesButton.on('submit', ajaxSaveNotes); function ajaxSaveNotes(e) { e.preventDefault(); axios .post(this.action) .then(res => { console.log(res.data); }) .catch(console.error); }
不幸的是,在使用axios制作post
时,需要将数据包含在这样的对象中,否则将不包含在请求中:
const SaveNotesButton = $('form.saveNotes'); SaveNotesButton.on('submit', ajaxSaveNotes); function ajaxSaveNotes(e) { e.preventDefault(); axios .post(this.action, { notes: this.children.hiddenNotes.value }) // Data added here .then(res => { console.log(res.data); }) .catch(console.error); }
必须尝试使用邮差或类似的东西来查询您的终点?
可能有一个可能的解释,为什么你的req.body
是未定义的。 你确定你的app.use(bodyParser.json())
和app.use(bodyParser.url...
是否写在你的app.use('***', router)
行之前?如果你把body parser中间件在你的路由器中间件之后,它本质上不会被调用,因为中间件是按照它们放在app.use
中的顺序调用的,所以你应该把你的bodyParser
放在你所有的路由器逻辑之前,BodyParser中间件然后调用所有其他的中间件包含所有路由器级别的中间件。
希望能帮助到你!
不知道你是如何定义你的路线,但我期望一个后路线如下所示:
const express = require('express'); const app = express(); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.post('/lessons/:lessonID/notes', (req, res) => { // now pass the req object to your function lessonController.updateNotes(req); });
你需要传递req对象到你的函数才能访问req.body …