DELETE Request
Overview
This guide illustrates the use of a DELETE request in JavaScript with the Fetch API. DELETE requests are typically used to remove resources from a server, making them essential for applications that involve data manipulation and maintenance.
Code
function deleteResource(apiUrl) {
fetch(apiUrl, {
method: "DELETE",
})
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
console.log("Resource deleted successfully");
})
.catch((error) => {
console.error("Fetch error:", error);
});
}
Example Usage
// Calling the function to delete a specific resource
deleteResource("https://api.example.com/data/123");
Code Description
The deleteResource
function is a JavaScript utility for making HTTP DELETE requests using the Fetch API. This function simplifies the process of deleting resources from a server. Below is an overview of its functionality:
Function Parameter:
apiUrl
: The URL of the resource to be deleted. It should include the unique identifier (ID) of the resource.
Fetch API Configuration:
- The function initiates a DELETE request to the provided
apiUrl
. - There's no need to set specific headers or a request body for a typical DELETE request.
Response Handling:
- The function checks the response status. If it's not OK (indicative of a successful request), it throws an error detailing the HTTP status.
- Logs a success message to the console if the resource is deleted successfully.
Error Handling:
- Catches and logs any errors encountered during the fetch operation, such as network issues or server errors.
This function can be used in various parts of a web application that require the removal of data from a server, such as in content management systems or user account deletions.