Answers for "fetch post request with html body"

12

how to send post request js fetch

componentDidMount() {
    // Simple POST request with a JSON body using fetch
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: 'React POST Request Example' })
    };
    fetch('https://jsonplaceholder.typicode.com/posts', requestOptions)
        .then(response => response.json())
        .then(data => this.setState({ postId: data.id }));
}
Posted by: Guest on May-22-2020
-1

fetch post form data

// It's almost copy paste ajax function,
// just select the right Form and set the right URL

document.getElementById('submitBtn').onclick = ajax

function ajax(e){
	e.preventDefault()

	// Get form element and create a formData object
	const form = document.getElementsByTagName('form')[0]
	const formData = {}

	// Get all input elements inside a form
    // and create key:value pairs inside formData
	form.querySelectorAll('input').forEach(element => {
		formData[element.name] = element.value
	})

	// Send data to your backend
	fetch(url, {
		method: "POST",
    	headers: {
    		"Content-Type": "application/json"
    	},
    	body: JSON.stringify(formData)
	})
}
Posted by: Guest on July-28-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language