HTTP Requests with Axios – Practical Guide with Examples

Axios is a popular JavaScript library that simplifies the process of sending and handling HTTP requests in both frontend and backend applications. It provides a user-friendly interface and a plethora of features that make working with APIs a breeze. In this blog, we’ll explore the power of Axios with practical examples, demonstrating how to perform GET, POST, PUT, and DELETE requests.

Getting Started:

Before diving into examples, let’s quickly set up Axios in your project. Axios can be used in both browser-based and Node.js environments. To include Axios in your project, you can use either a package manager like npm or yarn:

npm install axios
# or
yarn add axios

Once Axios is installed, you can import it into your JavaScript file or module:

// For CommonJS (Node.js) environment
const axios = require('axios');

// For ES6 (browser-based) environment
import axios from 'axios';

Example 1: Performing a GET Request

In this example, let’s make a simple GET request to an imaginary API that returns a list of users.

// GET request using Axios
axios.get('https://jsonplaceholder.typicode.com/users')
.then((response) => {
// Handle the success response
console.log(response.data);
})
.catch((error) => {
// Handle the error response
console.error('Error fetching data:', error);
});

Example 2: Performing a POST Request

Now, let’s demonstrate how to perform a POST request to create a new user on the server.

const newUser = {
name: 'John Doe',
email: '[email protected]',
};

axios.post('https://jsonplaceholder.typicode.com/users', newUser)
.then((response) => {
console.log('User created:', response.data);
})
.catch((error) => {
console.error('Error creating user:', error);
});

Example 3: Performing a PUT Request

Let’s update an existing user’s data using a PUT request.

const updatedUser = {
name: 'Jane Smith',
email: '[email protected]',
};

axios.put('https://jsonplaceholder.typicode.com/users/1', updatedUser)
.then((response) => {
console.log('User updated:', response.data);
})
.catch((error) => {
console.error('Error updating user:', error);
});

Example 4: Performing a DELETE Request

Lastly, let’s delete a user using a DELETE request.

const userIdToDelete = 1;

axios.delete(`https://jsonplaceholder.typicode.com/users/${userIdToDelete}`)
.then((response) => {
console.log('User deleted:', response.data);
})
.catch((error) => {
console.error('Error deleting user:', error);
});

 

Share