我有一个带有表单的html页面。当我用form.submit()提交数据时,一切正常。当我尝试使用fetch时,服务器输出的信息为未定义
委托单位:
<form id="form" action="/submit-reservation" method="POST">
<label for="name">Surname:</label><br>
<input type="text" name="name"><br>
<label for="address">Address:</label><br>
<input type="text" name="address"><br>
<label for="town">Town/City:</label><br>
<input type="text" name="town"><br>
<label for="email">Email address:</label><br>
<input type="email" name="email"><br><br>
<center>
<a onclick="form.submit();" class="button">Submit</a>
<a onclick="fetch('/submit-reservation', { method: 'POST', body: new FormData(form) });" class="button">Submit</a>
</center>
</form>
伺服器:
app.post("/submit-reservation", (req, res) => {
console.log(req.body);
res.end();
});
form.submit()函数返回:{姓名:',地址:“”,城镇:“ASDF”,电子邮件:“”}
提取返回:{}
我检查了客户端上的表单数据是否正确,结果正确。
编辑:这是我的代码后的解决方案
<form id="form" action="/submit-reservation" method="POST">
<label for="name">Surname:</label><br>
<input type="text" name="name"><br>
<label for="address">Address:</label><br>
<input type="text" name="address"><br>
<label for="town">Town/City:</label><br>
<input type="text" name="town"><br>
<label for="email">Email address:</label><br>
<input type="email" name="email"><br><br>
<center>
<a onclick="fetch('/submit-reservation', { method: 'POST', body: new URLSearchParams(new FormData(form)) });" class="button">Submit</a>
</center>
</form>
1条答案
按热度按时间0md85ypi1#
您的
form
元素没有enctype
属性,因此它默认将数据编码为application/x-www-form-urlencoded
。FormData
对象将被编码为multipart/form-data
。您需要:
FormData
替换为URLSearchParams
(将编码为application/x-www-form-urlencoded
)。multipart/form-data
的正文解析中间件添加到服务器端代码中。