1

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 class="news-container" enctype="multipart/form-data">
        <input type="checkbox" name=""><span>Featured Content</span></input>
        <br/>
        <br/>
        <input type="submit"  class="submit-btn"></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'
        }
    })
    
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.