I have gotten outside of GET and POST methods with Fetch. But I couldn't find any good DELETE and PUT example.
So, I ask you for it. Could you give a good example of DELETE and PUT methods with fetch. And explain it a little bit.
To make a POST or PUT request, we need to change fetch's default behavior (making a GET request). This is done by adding an object as a second argument in a fetch call. The method property in the object specifies the request method. We can set this to POST or PUT .
DELETE request using fetch with async/await This sends the same DELETE request using fetch, but this version uses an async function and the await javascript expression to wait for the promises to return (instead of using the promise then() method as above).
POST request using fetch API: To do a POST request we need to specify additional parameters with the request such as method, headers, etc. In this example, we'll do a POST request on the same JSONPlaceholder and add a post in the posts. It'll then return the same post content with an ID.
Fetch defaults to GET requests, but you can use all other types of requests, change the headers, and send data.
Here is a fetch POST
example. You can do the same for DELETE
.
function createNewProfile(profile) { const formData = new FormData(); formData.append('first_name', profile.firstName); formData.append('last_name', profile.lastName); formData.append('email', profile.email); return fetch('http://example.com/api/v1/registration', { method: 'POST', body: formData }).then(response => response.json()) } createNewProfile(profile) .then((json) => { // handle success }) .catch(error => error);
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