There are a few quite technical posts here on Forms, but they didn't work to solve my issue. I'm trying to send some form data on the request's body.
I'm aware of these options:
The first approach refreshes the page, the second approach sends a more convoluted encoding by default. This encoding isn't handled by bodyParser middleware in Express.
Last choice is getting each field's value by Id, and sending it as an object.
Is there any way to avoid writing some lines of code to get each element by Id, or maybe this is the right approach?
Using FormData is the easiest way of getting data from a form but it sends the data as multipart/form-data which your middleware cannot handle.
You can use a middleware like multer to handle that type of data.
If you can't use multer, you can take the data from the FormData object and put it in a URLSearchParams object to send the data.
var form = document.getElementById('form');
form.addEventListener('submit', function(e){
e.preventDefault();
var formData = new FormData(this);
var data = new URLSearchParams(formData);
fetch('',{
method: 'POST',
body: data
});
});
<form id="form">
Name: <input name="name">
Box: <input type="checkbox" name="box" value="box">
<button>Submit</button>
</form>