As the title says, I am trying to capture user's input through an HTML form and on submit, POST their data to an API.
I can successfully POST and get a response from the API, however none of my form data is being attached (at least I believe this is the ongoing issue).
Since this is practice I am using a free post API I found online at https://reqres.in/. All help is appreciated!
HTML
<form id="myForm">
<label for="myName">Send me your name:</label>
<input id="myName" name="name" value="Alex">
<br>
<label for="userId">your id:</label>
<input id="userId" name="id" value="123">
<br>
<label for="myJob">your name:</label>
<input id="myJob" name="job" value="Web Dev">
<br>
<input id="postSubmit" type="submit" value="Send Me!">
</form>
And here is my JavaScript
const thisForm = document.getElementById('myForm');
thisForm.addEventListener('submit', async function (e) {
e.preventDefault();
let response = await fetch('https://reqres.in/api/users', {
method: 'POST',
body: new FormData(thisForm)
});
let result = await response.json();
alert(result.message)
console.log(result)
});
Your form data was being appended to the POST request, but it was being appended in a format that reqres.in ignores. It seems reqres.in only processes a request body if it's a valid JSON string.
When you send a request with fetch that has a body set to new FormData(), your browser adds the Content-Type: multipart/form-data header to the request. reqres.in ignores multipart form data. The reqres.in API should respond with an error message to inform you that you've used a Content-Type that the API doesn't process correctly, rather than ignoring the body you supplied, creating a record and responding with 201 created. That's definitely a failing on their part.
Here's a working snippet using Content-Type: application/json. Beware, though, this isn't a robust way to convert a FormData object into corresponding JSON, and Object.fromEntries is only available in very modern browsers:
const thisForm = document.getElementById('myForm');
thisForm.addEventListener('submit', async function (e) {
e.preventDefault();
const formData = new FormData(thisForm).entries()
const response = await fetch('https://reqres.in/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.fromEntries(formData))
});
const result = await response.json();
console.log(result)
});
<form id="myForm">
<label for="myName">Send me your name:</label>
<input id="myName" name="name" value="Alex">
<br>
<label for="userId">your id:</label>
<input id="userId" name="id" value="123">
<br>
<label for="myJob">your name:</label>
<input id="myJob" name="job" value="Web Dev">
<br>
<input id="postSubmit" type="submit" value="Send Me!">
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With