繁体   English   中英

通过 HTML 表单发出 POST 请求时,请求正文为空

[英]Request body is empty when making a POST request via HTML form

我遇到了类似于这个问题和其他几个问题的症状,尽管答案对我没有帮助。 我正在尝试通过简单的 HTML 表单向 Node 应用程序提交密码,但请求正文一直返回为空。

服务器:

app.use(bodyParser.urlencoded({extended: true}));

router.post('/login', (req, res) => {
  console.log(req.body);
  console.log(req.headers['content-type']);
});

形式:

<form action="/login" method="post">
  <input type="password" id="password">
  <button type="submit">Log In</button>
</form>

如果我提交表格,我会得到以下信息:

{} // req.body
'application/x-www-form-urlencoded' // req.headers['content-type']

但是,如果我尝试卷曲端点, req.body得到一个非空的req.body

$ curl -X POST localhost:5000/login -d 'password=testpw'

// Output
{ password: 'testpw' }
'application/x-www-form-urlencoded'

我究竟做错了什么?

问题出在你的表格上

<form action="/login" method="post">
  <input type="password" id="password">
  <button type="submit">Log In</button>
</form>

您的input没有name元素

应该

<input name="password" type="password" id="password">

如果您的表单设置正确,如已接受的答案所示,但后端的请求正文仍为空,则应检查以确保您的后端正在使用某种正文解析器 如果您使用express.js ,一个示例修复是简单地添加:

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({limit: '5000mb', extended: true, parameterLimit: 100000000000}));

暂无
暂无

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

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