I have a html form whose data needs to be send to the server.I am using the encoding type as multipart/form-data
.
THe HTML form for the same is :
<form enctype="multipart/form-data">
<input type="checkbox" name=""><span>Featured Content</span></input>
<br/>
<br/>
<input type="submit" ></input>
</form>
The code for getting formData and sending the post request is :
const form=document.querySelector('.news-container');
submitbtn.addEventListener('click', (e) => {
e.preventDefault();
if(validateForm())
{
const data=new FormData(form);
postData(data);
}
})
async function postData(data) {
await fetch('http://localhost:5000/create', {
method: 'POST',
body: {
title: `${data.title}`, content: `${data.content}`
},
headers: {
'Content-Type': 'application/json'
}
})
}
CodePudding user response:
You can use the get
method from FormData
(docs) to read specific values, like so:
async function postData(data) {
await fetch('http://localhost:5000/create', {
method: 'POST',
body: {
title: `${data.get('title')}`, content: `${data.get('content')}`
},
headers: {
'Content-Type': 'application/json'
}
})
}
keep in mind that in the example you posted there are no title
or content
form fields.