Node.js:提交表单时接收空的主体

我意识到类似的问题已经在这里问了很多,但我仍然无法解决我的问题。 我真的不知道发生了什么事情。 我试图通过post请求从表单发送数据,但不断收到一个空的正文。 表单的Jade代码如下所示:( 编辑:添加enctype

  form(enctype="application/json" action="/test" method="post" name="login") table tr th label(for="username") Username td input(type="text" name="username" placeholder="username") tr th label(for="password") Password td input(type="password" name="password" placeholder="password") tr tr th td input(type="submit" value="Login") 

其中生成以下HTML代码( 编辑:添加HTML代码):

 <form enctype="application/json" action="/test" method="post" name="login"> <table> <tr> <th> <label for="username">Username</label> </th> <td> <input type="text" name="username" placeholder="username"> </td> </tr> <tr> <th> <label for="password">Password</label> </th> <td> <input type="password" name="password" placeholder="password"> </td> </tr> <tr></tr> <tr> <th></th> <td> <input type="submit" value="Login"> </td> </tr> </table> </form> 

所以我没有忘记name属性。

这是我如何处理请求:

 router.post('/test', function(req, res) { console.log('body:', req.body); res.render('login', {title: 'HK Test'}); }); 

打印机body {} 。 所以我确定收到了这个请求。

我也使用bodyparser:

 var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json());` 

然而,当我使用curl: curl -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:4000/login ,正文包含用户名和对象。 我从另一个工作项目中复制了Jade代码,所以我真的不明白我在做什么错误。

有没有人有一个想法可能是什么原因呢?

要在提交时将表单数据序列化为JSON,必须将此属性添加到表单中:

 enctype="application/json" 

否则,没有JS的任何帮助,您的表单数据将不会被封装为POST请求的JSON。

进一步阅读:

W3C JSON表单提交

你的请求不是/卷入请求testing

 http://localhost:4000/login 

改变它

 http://localhost:4000/test 

你忘记了逗号

  form(action="/test", method="post", name="login")