📜  js fetch delete - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:58.582000             🧑  作者: Mango

JS Fetch DELETE

Fetch API is a modern, promise-based JavaScript API for making HTTP requests. It provides a simple and concise way to fetch resources asynchronously across the network. In this tutorial, we will learn how to use the DELETE method with Fetch API in JavaScript.

Syntax
fetch(url, {
  method: 'DELETE'
})
.then(response => {
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
})
.catch(error => {
  console.error('There was an error!', error);
});
Explanation

The fetch() function takes one mandatory argument — the URL from which to fetch the resource — and an optional second argument in the form of an options object. In the options object, we specify the request method as 'DELETE' to tell the server that we want to delete the resource at the specified URL.

The DELETE method is used to delete a resource identified by a URI. A successful response to a DELETE method is HTTP 204 (No Content).

We can then chain a .then() method to extract the JSON content from the response using the .json() method. In addition, we can use .catch() method to catch errors that occur during the fetch.

Example
fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'DELETE'
})
.then(response => {
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
})
.then(data => {
  console.log(data);
})
.catch(error => {
  console.error('There was an error!', error);
});

In this example, we are deleting a post with ID 1 from the JSONPlaceholder API using the DELETE method. If the request is successful, the response will be an empty object {} with an HTTP status code of 204.

Conclusion

Fetch API provides a powerful and flexible way to make HTTP requests in JavaScript. With the DELETE method, we can easily delete resources from the server in a simple and concise manner.