Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Fetch DELETE and PUT requests

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.

like image 817
Kirill Stas Avatar asked Oct 27 '16 12:10

Kirill Stas


People also ask

How do you do a PUT request with Fetch?

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 .

How do you send delete request using Fetch?

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).

How do I send a POST request with Fetch?

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.

Is JavaScript fetch a GET request?

Fetch defaults to GET requests, but you can use all other types of requests, change the headers, and send data.


1 Answers

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); 
like image 94
FlatLander Avatar answered Nov 02 '22 11:11

FlatLander