I have an html page with a form. When i submit the data with form.submit() everthing works fine. When I try to use fetch the server outputs the info as undefined
Client:
<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();" >Submit</a>
<a onclick="fetch('/submit-reservation', { method: 'POST', body: new FormData(form) });" >Submit</a>
</center>
</form>
Server:
app.post("/submit-reservation", (req, res) => {
console.log(req.body);
res.end();
});
form.submit() returns: { name: '', address: '', town: 'ASDF', email: '' }
fetch returns: {}
I checked to see if the formdata was correct on the client and it was.
Edit: Here is my code after the solution
<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)) });" >Submit</a>
</center>
</form>
CodePudding user response:
Your form
element has no enctype
attribute so it defaults to encoding data as application/x-www-form-urlencoded
.
A FormData
object will be encoded as multipart/form-data
.
You need to either:
- Replace
FormData
withURLSearchParams
(which will be encoded asapplication/x-www-form-urlencoded
). - Add body parsing middleware that supports
multipart/form-data
to your server-side code.