简体   繁体   English

Express.js + body-parser:POST请求中的空req.body

[英]Express.js + body-parser: empty req.body from POST request

I am using Express and body-parser middleware to process incoming requests. 我正在使用Expressbody-parser中间件来处理传入的请求。 On the front end, I have a form that's just a hidden input and a submit button (written in Pug): 在前端,我有一个表单,只是一个隐藏的输入和一个提交按钮(用Pug编写):

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")

On the backend, I have the Express app using body-parser: 在后端,我有使用body-parser的Express应用程序:

const bodyParser = require('body-parser');
// ...
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

And the route processing the incoming request: 并处理传入请求的路由:

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' });
}

When I try to use req.body in updateNotes , the body is an empty object, but should at least have the property hiddenNotes with the value "test" . 当我尝试使用req.bodyupdateNotes ,身体是一个空的对象,但至少应该具备的使用性能hiddenNotes与价值"test" Please comment if you have any questions or think you see the problem! 如果您有任何疑问或认为自己有问题,请发表评论!

[UPDATED] [更新]

This was a silly mistake, I forgot I had written a separate event handler for when this form gets submitted - it just took me posting on SO before I went through all of my code :) The event handler uses axios and looks like this: 这是一个愚蠢的错误,我忘记了为提交此表单时编写的单独的事件处理程序-在我处理所有代码之前,我只是在SO上发布:)事件处理程序使用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);
}

Unfortunately, when making post s with axios, you need to include the data in an object like this, or else it won't be included in the request: 不幸的是,当使post与爱可信S,你需要在这样一个对象的数据,否则将不被包括在请求:

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);
}

必须尝试使用​​Postman或类似工具查询终点吗?

There could be one possible explanation for why your req.body is undefined. 关于为什么您的req.body未定义,可能有一种解释。 Are you sure your app.use(bodyParser.json()) and app.use(bodyParser.url... are written before your app.use('***', router) lines? If you put the body parser middleware AFTER your router middleware it essentially won't get called because middleware are called in the order they are put in app.use . So you should place your bodyParser before all your router logic. BodyParser middleware then calls all the other middleware (with the req.body populated) that come after it including all your router level middleware. 您确定您的app.use(bodyParser.json())app.use(bodyParser.url...是在您的app.use('***', router)行之前编写的吗?在路由器中间件之后,它基本上不会被调用,因为按照在app.use中放置它们的顺序来调用中间件。因此,应将bodyParser所有路由器逻辑之前。BodyParser中间件然后调用所有其他中间件(带有req.body填充),包括所有路由器级中间件。

Hope it helps! 希望能帮助到你!

Not sure how you are defining your routes but I would expect a post route to look like the following: 不确定您如何定义路线,但是我希望发布路线看起来像下面这样:

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);
});

You need to pass the req object to your function to be able to access req.body... 您需要将req对象传递给函数才能访问req.body ...

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

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