When developing web applications, managing resources often requires the ability to delete data. HTTP DELETE requests are specifically designed for this purpose, allowing you to remove resources from a server. DELETE requests are essential in various scenarios, such as deleting user accounts, removing items from a database, or clearing logs.
Axios, a popular JavaScript library, simplifies the process of making HTTP DELETE requests by providing a promise-based interface. This makes it easy to handle asynchronous operations in JavaScript. In this comprehensive guide, we’ll explore how to use Axios to make DELETE requests, handle responses and errors, and configure requests to suit different use cases.
Understanding HTTP DELETE Requests
An HTTP DELETE request is a method used to request the removal of a resource from a server. When a DELETE request is made, the server processes the request and deletes the specified resource. DELETE requests are idempotent, meaning that making multiple identical requests will have the same effect as a single request.
Use Cases for DELETE Requests
DELETE requests are used in various scenarios, such as:
- Deleting User Accounts: Removing user accounts from a database.
- Removing Items: Deleting products, posts, or any other items from a database.
- Clearing Logs: Deleting log files or records.
- Revoking Access: Removing access permissions or tokens.
Setting Up Axios in Your Project
To start using Axios for making DELETE requests, you need to set it up in your project. You can install Axios via npm/yarn or include it via a CDN.
Installing Axios via npm/yarn
If you’re using npm or yarn, you can install Axios with a simple command.
Using npm:
npm install axios
Using yarn:
yarn add axios
After installation, you can import Axios in your JavaScript files:
import axios from 'axios';
Setting Up Axios via CDN
If you prefer to include Axios via a Content Delivery Network (CDN), you can add the following script tag to your HTML file:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
This approach is useful for quick setups or for use in environments where a package manager is not available. When included via CDN, Axios is available globally as axios.
Making Simple DELETE Requests
Once Axios is set up in your project, making a DELETE request is straightforward. Here is a basic example.
Using npm/yarn:
import axios from 'axios';
// Function to delete data from an API
const deleteData = async () => {
try {
const response = await axios.delete('https://jsonplaceholder.typicode.com/posts/1');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error deleting data:', error);
}
};
// Call the function to delete data
deleteData();
Using CDN:
<script>
// Function to delete data from an API
const deleteData = async () => {
try {
const response = await axios.delete('https://jsonplaceholder.typicode.com/posts/1');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error deleting data:', error);
}
};
// Call the function to delete data
deleteData();
</script>
In this example, we define a function deleteData that sends a DELETE request to the URL https://jsonplaceholder.typicode.com/posts/1. The axios.delete method is used to send the DELETE request. The argument is the URL endpoint of the resource to be deleted. The await keyword ensures that the function waits for the request to complete before continuing. The response data is logged to the console if the request is successful, and any errors are caught and logged.
Handling Responses and Errors
When you make a request with Axios, the response object contains several properties, including data, status, statusText, headers, and config. These properties provide detailed information about the response, allowing you to handle it appropriately.
Here’s an example of how to handle responses and errors in Axios:
Using npm/yarn:
import axios from 'axios';
// Function to delete data and handle responses and errors
const deleteData = async () => {
try {
const response = await axios.delete('https://jsonplaceholder.typicode.com/posts/1');
console.log('Data:', response.data);
console.log('Status:', response.status);
} catch (error) {
if (error.response) {
// Server responded with a status other than 2xx
console.error('Error response data:', error.response.data);
console.error('Error response status:', error.response.status);
} else if (error.request) {
// No response received from server
console.error('Error request:', error.request);
} else {
// Other errors
console.error('Error message:', error.message);
}
}
};
// Call the function to delete data
deleteData();
Using CDN:
<script>
// Function to delete data and handle responses and errors
const deleteData = async () => {
try {
const response = await axios.delete('https://jsonplaceholder.typicode.com/posts/1');
console.log('Data:', response.data);
console.log('Status:', response.status);
} catch (error) {
if (error.response) {
// Server responded with a status other than 2xx
console.error('Error response data:', error.response.data);
console.error('Error response status:', error.response.status);
} else if (error.request) {
// No response received from server
console.error('Error request:', error.request);
} else {
// Other errors
console.error('Error message:', error.message);
}
}
};
// Call the function to delete data
deleteData();
</script>
In this example, we extend the deleteData function to handle different types of errors. The axios.delete method is used to make the request, and the response data and status are logged to the console if successful.
The catch block differentiates between three types of errors:
- Error response: The server responded with a status code other than 2xx.
- Error request: The request was made, but no response was received.
- Other errors: Any other errors that might occur, such as network issues.
By handling these different error scenarios, you can ensure that your application responds appropriately to various error conditions.
Configuring DELETE Requests
In many cases, you need to configure your DELETE requests with custom headers. Axios allows you to easily add these configurations to your requests.
Using npm/yarn:
import axios from 'axios';
// Function to delete data with custom headers
const deleteData = async () => {
try {
const response = await axios.delete('https://jsonplaceholder.typicode.com/posts/1', {
headers: {
'Authorization': 'Bearer token'
}
});
console.log('Response data:', response.data);
} catch (error) {
console.error('Error deleting data:', error);
}
};
// Call the function to delete data
deleteData();
Using CDN:
<script>
// Function to delete data with custom headers
const deleteData = async () => {
try {
const response = await axios.delete('https://jsonplaceholder.typicode.com/posts/1', {
headers: {
'Authorization': 'Bearer token'
}
});
console.log('Response data:', response.data);
} catch (error) {
console.error('Error deleting data:', error);
}
};
// Call the function to delete data
deleteData();
</script>
In this example, we define a function deleteData that sends a DELETE request to the URL https://jsonplaceholder.typicode.com/posts/1. Additionally, custom headers are added using the headers option. The Authorization header is set to a bearer token for authentication purposes. The response data is logged to the console if the request is successful, and any errors are caught and logged.
Advanced Usage of DELETE Requests
Using Axios Interceptors
Interceptors allow you to run your code or modify the request or response before they are handled by then or catch. This is useful for tasks like adding authorization tokens to requests or logging request and response details.
Using npm/yarn:
import axios from 'axios';
// Add a request interceptor
axios.interceptors.request.use(
config => {
console.log('Request made with ', config);
config.headers.Authorization = 'Bearer token';
return config;
},
error => {
return Promise.reject(error);
}
);
// Add a response interceptor
axios.interceptors.response.use(
response => {
console.log('Response received', response);
return response;
},
error => {
console.log('Error response', error.response);
return Promise.reject(error);
}
);
// Function to make a request
const deleteData = async () => {
try {
const response = await axios.delete('https://jsonplaceholder.typicode.com/posts/1');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error deleting data:', error);
}
};
// Call the function to delete data
deleteData();
Using CDN:
<script>
// Add a request interceptor
axios.interceptors.request.use(
config => {
console.log('Request made with ', config);
config.headers.Authorization = 'Bearer token';
return config;
},
error => {
return Promise.reject(error);
}
);
// Add a response interceptor
axios.interceptors.response.use(
response => {
console.log('Response received', response);
return response;
},
error => {
console.log('Error response', error.response);
return Promise.reject(error);
}
);
// Function to make a request
const deleteData = async () => {
try {
const response = await axios.delete('https://jsonplaceholder.typicode.com/posts/1');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error deleting data:', error);
}
};
// Call the function to delete data
deleteData();
</script>
In this example, we add request and response interceptors using axios.interceptors.request.use and axios.interceptors.response.use methods. The request interceptor logs the request configuration and adds an authorization header. The response interceptor logs the response details and handles errors. By using interceptors, you can centralize and streamline request and response handling logic, making your code cleaner and more maintainable.
Conclusion
In this article, we explored how to make HTTP DELETE requests using Axios. We covered the basics of setting up Axios, making simple DELETE requests, handling responses and errors, configuring DELETE requests with headers, and using interceptors for advanced request handling.
The examples and concepts discussed provide a solid foundation for working with Axios in your projects. However, there is much more to explore. I encourage you to experiment further with Axios, integrating it into your applications to handle API interactions efficiently and effectively.