DeveloperBreeze

Introduction

Axios is a popular JavaScript library used to make HTTP requests from the browser and Node.js. It provides a simple and clean API for making asynchronous requests to REST APIs, handling responses, and managing errors. In this tutorial, we’ll explore how to get started with Axios, covering the basics of installation, making requests, handling responses, and more.

Prerequisites

To follow this tutorial, you should have a basic understanding of JavaScript, including concepts like functions, promises, and asynchronous programming. Familiarity with HTTP methods (GET, POST, etc.) will also be helpful.

1. Installing Axios

Axios can be installed via npm if you're using Node.js or directly included in your HTML file if you're working in the browser.

1.1 Installing via npm

If you're working on a Node.js project, you can install Axios using npm:

npm install axios

1.2 Including in an HTML File

If you're working in the browser, you can include Axios directly via a CDN:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

2. Making Your First Request

Let's start by making a simple GET request to a public API using Axios.

Example:

axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

In this example:

  • We use axios.get() to send a GET request to the specified URL.
  • The then() method handles the successful response, where response.data contains the returned data.
  • The catch() method handles any errors that occur during the request.

3. Making POST Requests

Axios makes it easy to send POST requests with data. Here's how you can send a POST request to create a new resource.

Example:

axios.post('https://jsonplaceholder.typicode.com/posts', {
    title: 'New Post',
    body: 'This is the content of the new post.',
    userId: 1
  })
  .then(response => {
    console.log('Post created:', response.data);
  })
  .catch(error => {
    console.error('Error creating post:', error);
  });

In this example:

  • We use axios.post() to send a POST request to the API endpoint.
  • The second argument to axios.post() is the data object that will be sent with the request.

4. Handling Responses

Axios provides a variety of ways to handle responses, allowing you to work with the data returned by the server.

4.1 Accessing Response Data

The response object contains several useful properties:

  • data: The actual data returned by the server.
  • status: The HTTP status code.
  • statusText: The HTTP status text.
  • headers: The headers sent by the server.

Example:

axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    console.log('Data:', response.data);
    console.log('Status:', response.status);
    console.log('Headers:', response.headers);
  });

5. Working with Query Parameters

You can easily send query parameters with your GET requests using Axios.

Example:

axios.get('https://jsonplaceholder.typicode.com/posts', {
    params: {
      userId: 1
    }
  })
  .then(response => {
    console.log('Posts by user 1:', response.data);
  })
  .catch(error => {
    console.error('Error fetching posts:', error);
  });

In this example:

  • We pass an object with query parameters to the params option in axios.get().

6. Setting Request Headers

Custom headers can be set in Axios requests, which is useful when working with APIs that require authentication tokens or specific content types.

Example:

axios.get('https://jsonplaceholder.typicode.com/posts/1', {
    headers: {
      'Authorization': 'Bearer YOUR_TOKEN_HERE'
    }
  })
  .then(response => {
    console.log('Post data:', response.data);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

7. Making Concurrent Requests

Axios allows you to make multiple requests simultaneously using axios.all() and axios.spread().

Example:

axios.all([
    axios.get('https://jsonplaceholder.typicode.com/posts/1'),
    axios.get('https://jsonplaceholder.typicode.com/posts/2')
  ])
  .then(axios.spread((post1, post2) => {
    console.log('Post 1:', post1.data);
    console.log('Post 2:', post2.data);
  }))
  .catch(error => {
    console.error('Error fetching data:', error);
  });

In this example:

  • We use axios.all() to send multiple requests.
  • The axios.spread() function is used to handle the responses separately.

8. Handling Errors

Error handling is crucial when working with HTTP requests. Axios provides several ways to manage errors, including checking the response status and handling network errors.

Example:

axios.get('https://jsonplaceholder.typicode.com/invalid-url')
  .then(response => {
    console.log('Data:', response.data);
  })
  .catch(error => {
    if (error.response) {
      console.error('Error Response:', error.response.data);
    } else if (error.request) {
      console.error('No Response:', error.request);
    } else {
      console.error('Error:', error.message);
    }
  });

9. Creating an Axios Instance

If you're making multiple requests to the same base URL or with the same configuration, you can create an Axios instance.

Example:

const apiClient = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 1000,
  headers: { 'X-Custom-Header': 'foobar' }
});

apiClient.get('/posts/1')
  .then(response => {
    console.log('Post:', response.data);
  });

In this example:

  • We create an Axios instance with a base URL and custom configuration.
  • The instance can be reused for multiple requests, simplifying your code.

Conclusion

Axios is a powerful and flexible library for making HTTP requests in JavaScript. Whether you're fetching data, submitting forms, or handling complex API interactions, Axios simplifies the process with its clean and consistent API. By mastering the basics covered in this tutorial, you'll be well-equipped to use Axios in your own projects.


Next Steps

  • Experiment with making requests to different APIs.
  • Explore more advanced Axios features like interceptors and request cancellation.
  • Consider using Axios in a framework like React or Vue.js for even more powerful applications.

Additional Resources


This tutorial provides a comprehensive introduction to using Axios for making HTTP requests in JavaScript. By understanding these basics, you'll be able to integrate Axios into your applications, streamlining your API interactions and improving your development workflow.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
javascript

Installing a Code Editor (e.g., VS Code)

  • Example:
     console.log("Hello, World!");

Dec 10, 2024
Read More
Code
javascript

Dynamic and Responsive DataTable with Server-Side Processing and Custom Styling

  • responsive: true makes the table adapt to different screen sizes.
  • serverSide: true enables server-side pagination, sorting, and filtering.
  • processing: true displays a processing indicator while fetching data.

Oct 24, 2024
Read More
Tutorial
php

Handling HTTP Requests and Raw Responses in Laravel

composer create-project --prefer-dist laravel/laravel example-app

Make sure to have php and composer installed on your machine.

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

   https://api.etherscan.io/api?module=proxy&action=eth_gasPrice&apikey=YOUR_API_KEY

These endpoints give you the flexibility to retrieve detailed blockchain data and customize your applications accordingly.

Oct 24, 2024
Read More
Article
javascript

20 Useful Node.js tips to improve your Node.js development skills:

No preview available for this content.

Oct 24, 2024
Read More
Tutorial
javascript python

How to Build a Fullstack App with Flask and React

You can add more CRUD operations like Update and **

Delete** to complete the Task Manager app.

Sep 30, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

Here are some common use cases where AJAX can be effectively used:

AJAX allows form submissions to be processed in the background without reloading the page.

Sep 18, 2024
Read More
Tutorial
javascript

Advanced JavaScript Tutorial for Experienced Developers

console.log(this); // In a browser: Window object

When this is used inside a function, it depends on how the function is called:

Sep 02, 2024
Read More
Tutorial
javascript

Mastering console.log Advanced Usages and Techniques

You can measure the time it takes for a block of code to execute using console.time and console.timeEnd. This is useful for performance testing.

console.time('loop');
for (let i = 0; i < 1000000; i++) {
  // Some operation
}
console.timeEnd('loop'); // Output: loop: <time in ms>

Sep 02, 2024
Read More
Cheatsheet

REST API Cheatsheet: Comprehensive Guide with Examples

No preview available for this content.

Aug 24, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

  • Use memory over storage for temporary variables.

  • Group multiple storage updates in a single transaction.

Aug 22, 2024
Read More
Cheatsheet

Comprehensive React Libraries Cheatsheet

No preview available for this content.

Aug 21, 2024
Read More
Tutorial
bash

Creating and Managing Bash Scripts for Automation

   #!/bin/bash

   echo "Enter a number:"
   read number

   if [ $number -gt 10 ]; then
       echo "The number is greater than 10."
   else
       echo "The number is 10 or less."
   fi

Loops enable you to repeat a block of code multiple times.

Aug 19, 2024
Read More
Tutorial
javascript nodejs

Building a React Application with Vite and Tailwind CSS

npm create vite@latest my-react-app -- --template react

Navigate into your project directory:

Aug 14, 2024
Read More
Tutorial
go

Building a RESTful API with Go and Gorilla Mux

package main

type Book struct {
	ID     string `json:"id"`
	Title  string `json:"title"`
	Author string `json:"author"`
	Year   string `json:"year"`
}

Create a new file named main.go and set up the basic structure of the application:

Aug 12, 2024
Read More
Code
javascript

React Custom Hook for API Requests

No preview available for this content.

Aug 12, 2024
Read More
Code
python

Python Logging Snippet

- FileHandler: Writes logs to a file (logs/app.log), useful for long-term storage and analysis.

- StreamHandler: Outputs logs to the console, providing immediate feedback.

Aug 08, 2024
Read More
Code
javascript

Weather App with Node.js

Create a new directory for your project and navigate into it:

mkdir weather-app
cd weather-app

Aug 08, 2024
Read More
Tutorial
python

Creating a Simple REST API with Flask

python -m venv venv

Activate the virtual environment:

Aug 03, 2024
Read More
Code
javascript

Fetching Chuck Norris Jokes from API in JavaScript

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!