通过HTML表单进行POST请求时,请求体为空

13

我遇到了类似于这个问题和其他几个问题的症状,但答案并没有帮助我。我正在尝试通过一个简单的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']

不过,如果我尝试用Curl访问该端点,我会得到一个非空的req.body

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

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

我做错了什么?


Express 的哪个版本? - Alex
Express版本4 - ericgio
2个回答

31

问题出在您的表格中。

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

3
哎呀呀呀呀。谢谢。 - ericgio
1
这可能很琐碎,但它救了我。谢谢 :) - Tore Binarflame
嗨,我有同样的问题,但在我的情况下,我有名称,每个输入都有一个ID,我使用了express.json()作为body解析器,但仍然得到空的body。你能给我一些线索吗? - Alexandru DuDu

5

如果你的表单已经按照接受答案中所示进行了正确设置,但是后端仍然收到空请求体,则应该检查确保后端使用了某种请求体解析器。如果你正在使用express.js,一个简单的修复方法就是添加以下代码:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接