使用fetch提交FormData无效,但form.submit()正常的问题排查
表单提交异常:fetch提交服务器返回undefined,form.submit()正常
我有一个带表单的HTML页面,用form.submit()提交数据完全正常,但用fetch提交时,服务器打印的req.body是空对象。
客户端代码
<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>
服务端代码(Express)
app.post("/submit-reservation", (req, res) => { console.log(req.body); res.end(); });
现象
form.submit()提交后,服务器输出:{ name: '', address: '', town: 'ASDF', email: '' }- fetch提交后,服务器输出:
{} - 已确认客户端的FormData数据是正确的。
问题原因
form.submit()默认会把表单数据编码成application/x-www-form-urlencoded格式发送;但直接把FormData传给fetch的body时,fetch会自动将请求头的Content-Type设为multipart/form-data,如果服务端没配置对应解析中间件(比如Express的multer),就无法解析出req.body,导致输出空对象。
解决方法
将FormData转换为URLSearchParams,这样fetch会自动设置Content-Type为application/x-www-form-urlencoded,和form.submit()的提交格式一致,服务端就能正常解析数据了。
解决后的客户端代码
<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>
内容的提问来源于stack exchange,提问作者Joospis
相关产品推荐
相关产品推荐

