Skip to content
Axios Getting Started — Complete Beginner's Guide to HTTP Requests

Axios Getting Started — Complete Beginner's Guide to HTTP Requests

DodaTech Updated Jun 6, 2026 9 min read

Axios is a promise-based HTTP client for the browser and Node.js that makes sending HTTP requests simple — with automatic JSON parsing, request cancellation, timeout support, and interceptors built in.

What You’ll Learn

By the end of this tutorial, you’ll install Axios, make GET, POST, PUT, and DELETE requests, handle responses and errors properly, understand the response/error object structure, use async/await, and know when to choose Axios over the Fetch API.

New to HTTP requests? No problem. This tutorial explains every concept from the ground up. You just need basic JavaScript knowledge.

Why Axios Matters

Every modern web application communicates with servers. When you log in, the app sends your credentials to a server. When you load a profile page, the app fetches data from an API. When you submit a form, the app POSTs the data and waits for a response.

This communication happens via HTTP requests — the language browsers and servers speak.

You could use the built-in fetch() function, but it has quirks: it doesn’t throw errors on 404/500 responses, requires manual JSON parsing, and has no built-in timeout. Axios fixes all of this with a cleaner, more predictable API.

Real-world use: Durga Antivirus Pro uses Axios to communicate with its cloud threat database. When scanning a file, it sends the file hash to the API via Axios, reads the response to determine if the file is malicious, and handles errors gracefully if the network is down.

Where This Fits in Your Learning Path

    flowchart LR
    A["JavaScript Basics"] --> B["**Axios Getting Started**"]
    B --> C["Requests, Responses & Config"]
    C --> D["Interceptors & Error Handling"]
    D --> E["Axios Advanced"]
    E --> F["Full-Stack API Apps"]
    style B fill:#f97316,stroke:#c2410c,color:#fff
    style A fill:#e5e7eb,stroke:#9ca3af,color:#374151
    style F fill:#22c55e,stroke:#16a34a,color:#fff
  

What is Axios?

Imagine you’re at a restaurant. You (the browser) tell the waiter (Axios) what you want. The waiter goes to the kitchen (the server), brings back your food (the response), and if something goes wrong (burnt food, closed kitchen), they tell you clearly what happened.

Without Axios, you’d have to go to the kitchen yourself, check if the chef is there, grab your food, and figure out what went wrong if the kitchen is locked.

HTTP requests work the same way. Your browser sends a request to a server, the server processes it and sends back a response. Axios makes this process clean and predictable.

Key Features at a Glance

FeatureWhat it means for you
Auto JSON parsingJSON responses are automatically converted to JavaScript objects
Error handlingNon-2xx responses throw errors you can catch
TimeoutsBuilt-in timeout config — no extra code needed
InterceptorsRun code before every request or after every response
CancellationCancel in-flight requests when the user navigates away
Works everywhereSame API in browsers and Node.js

Installation

CDN (Easiest Way to Start)

Add a single <script> tag to your HTML:

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

After this tag, axios is available as a global variable. Open your browser console and type axios — you’ll see the Axios module.

npm (For Node.js or Build Systems)

npm install axios
import axios from 'axios'
// or: const axios = require('axios')

Making Your First GET Request

A GET request retrieves data from a server. Think of it like asking “give me this information.”

import axios from 'axios'

const response = await axios.get('https://api.example.com/users')
console.log(response.data)   // The server's response body
console.log(response.status) // 200 (means OK)

Let’s try it with a real, working API:

// Using JSONPlaceholder — a free fake API for testing
async function getPosts() {
  const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1')
  console.log('Data:', response.data)
  console.log('Status:', response.status)
}

getPosts()

Expected output:

Data: { userId: 1, id: 1, title: "...", body: "..." }
Status: 200

What’s happening step by step:

  1. axios.get() sends an HTTP GET request to the URL
  2. The server processes the request and sends back a JSON response
  3. Axios automatically parses the JSON into a JavaScript object
  4. The parsed data is available at response.data

The Four Main HTTP Methods

MethodWhat it doesAnalogy
GETRetrieve dataLooking at a menu
POSTCreate new dataAdding a new item to the menu
PUTReplace existing dataChanging an entire menu item
DELETERemove dataRemoving an item from the menu

GET — Fetch Data

const response = await axios.get('https://api.example.com/users')
console.log(response.data) // Array of users

POST — Create Data

const newUser = {
  name: 'Alice',
  email: 'alice@example.com'
}

const response = await axios.post('https://api.example.com/users', newUser)
console.log(response.status) // 201 (Created)
console.log(response.data)   // The created user (with an id)

The second argument to axios.post() is the request body — the data you’re sending to the server. Axios automatically serializes it to JSON.

PUT — Replace Data

const updatedUser = {
  name: 'Alice Updated',
  email: 'alice.new@example.com'
}

const response = await axios.put('https://api.example.com/users/1', updatedUser)
console.log(response.data) // The updated user

PUT replaces the entire resource at /users/1 with the data you provide.

DELETE — Remove Data

const response = await axios.delete('https://api.example.com/users/1')
console.log(response.status) // 200 or 204 (No Content)

DELETE usually returns an empty body with status 200 or 204.


The Response Object

Every successful Axios request returns a response object with these properties:

const res = await axios.get('https://api.example.com/data')

res.data        // The response body (auto-parsed JSON)
res.status      // HTTP status code (200, 201, 404, etc.)
res.statusText  // Status text ("OK", "Not Found")
res.headers     // Response headers as an object
res.config      // The request configuration that was used

res.data is the one you’ll use most. If the server returns JSON, this is already a JavaScript object — no JSON.parse() needed.


Error Handling

This is where Axios shines over the Fetch API. With Axios, any non-2xx status code (like 404 or 500) throws an error automatically:

try {
  const res = await axios.get('https://api.example.com/nonexistent')
} catch (error) {
  if (error.response) {
    // The server responded with an error status
    console.log('Status:', error.response.status) // 404
    console.log('Data:', error.response.data)     // Error body
  } else if (error.request) {
    // Request was sent but no response received
    console.log('Network error:', error.message)
  } else {
    // Something went wrong setting up the request
    console.log('Setup error:', error.message)
  }
}

Three possible error scenarios:

  1. error.response exists — The server responded but with an error code (4xx or 5xx). You can check error.response.status and error.response.data.

  2. error.request exists but no error.response — The request was sent but never received a response. This happens with network failures, timeouts, or the server being down.

  3. Neither exists — Something went wrong before the request was sent (bad configuration, invalid URL).


Using async/await

Axios is promise-based, so it works naturally with async/await:

async function fetchUsers() {
  try {
    const { data } = await axios.get('/api/users')
    return data
  } catch (error) {
    console.error('Failed to fetch users:', error.message)
    throw error
  }
}

The { data } syntax is destructuring — it pulls the data property from the response object directly. It’s equivalent to const response = await axios.get(...) then const data = response.data.


Axios vs Fetch API

FeatureAxiosFetch API
JSON parsingAutomaticManual (response.json())
Error on 4xx/5xxYes (throws)No (only network errors)
TimeoutBuilt-in timeout optionManual via AbortSignal
Request cancellationBuilt-inManual AbortController
Upload progressonUploadProgressComplex (via streams)
InterceptorsYesNot available
Bundle size~14KB gzipped0KB (native)

When to use Axios: You need automatic JSON parsing, consistent error handling, interceptors for auth tokens/logging, request timeouts, or upload progress tracking.

When to use Fetch: Bundle size is critical and you target only modern browsers, you prefer native APIs, or you need streaming responses.


Common Mistakes Beginners Make

1. Not awaiting the promise

// Wrong: data is a Promise, not the response
const data = axios.get('/api/users')

// Correct: await resolves the promise
const response = await axios.get('/api/users')

2. Forgetting that non-2xx responses throw

// This will throw on 404 — wrap in try/catch
const res = await axios.get('/api/users/999')

Unlike fetch(), Axios throws on any non-2xx status. Always handle errors.

3. Not checking for network errors separately

catch (error) {
  // Always check if error.response exists first
  if (error.response) {
    // Server responded with error
  } else if (error.request) {
    // Network issue
  }
}

4. Passing body to GET requests

// Wrong: GET requests don't have a body
axios.get('/api/users', { name: 'Alice' })

// Correct: use params option
axios.get('/api/users', { params: { name: 'Alice' } })

5. Forgetting Content-Type header for POST

Axios auto-detects content type for objects, but if you send non-JSON data, set the header manually.


Practice Questions

  1. What does response.data contain? The response body, automatically parsed from JSON into a JavaScript object.

  2. How does Axios handle non-2xx HTTP status codes? It throws an error. You catch it in a try/catch block and check error.response.status.

  3. What’s the difference between error.response and error.request? error.response exists when the server responded (but with an error code). error.request exists when the request was sent but no response was received (network failure).

  4. What does the { data } destructuring syntax do? It extracts the data property from the response object directly, saving you from writing response.data.

  5. When would you choose Fetch over Axios? When bundle size is critical, you target only modern browsers, or you need streaming responses.

Challenge

Build a script that:

  • Fetches a list of posts from https://jsonplaceholder.typicode.com/posts
  • Fetches user details for each post’s userId
  • Combines the data: each post should include the user’s name
  • Handles errors at each step
  • Logs the final combined array

FAQ

Is Axios still maintained?

Yes. Axios is actively maintained with regular releases. Version 1.x is stable and production-ready with an active community.

Does Axios work with TypeScript?

Yes. Axios includes TypeScript definitions out of the box. Types like AxiosResponse, AxiosError, and AxiosInstance are available.

How does Axios handle CORS?

Axios respects the browser’s CORS policy — it cannot bypass it. The server must include the appropriate CORS headers. Axios does support withCredentials: true for sending cookies cross-origin.

Can I use Axios in React Native?

Yes. Axios works in React Native without any additional configuration.

What is the difference between axios() and axios.get()?

axios(config) makes a request with a full configuration object. axios.get(url, config) is a convenience wrapper. They are equivalent.

Try It Yourself

Create an HTML file with this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Axios Demo</title>
  <script src="https://cdn.jsdelivr.net/npm/axios@1.7.0/dist/axios.min.js"></script>
</head>
<body>
  <h1>Axios GET Request</h1>
  <button onclick="fetchData()">Fetch Post</button>
  <pre id="output" style="background: #f4f4f4; padding: 1rem; border-radius: 8px; margin-top: 1rem;"></pre>

  <script>
    async function fetchData() {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1')
        document.getElementById('output').textContent =
          JSON.stringify(response.data, null, 2)
      } catch (error) {
        document.getElementById('output').textContent = 'Error: ' + error.message
      }
    }
  </script>
</body>
</html>

What to expect: Click the button to fetch a sample post from JSONPlaceholder. The response (title, body, userId) appears formatted in the <pre> block.


What’s Next

TutorialWhat You’ll Learn
Requests, Responses & ConfigCustom config, defaults, instances
Interceptors & Error HandlingAuth tokens, logging, retry logic
Axios AdvancedCancellation, progress tracking

Related topics: JavaScript promises & async/await, REST APIs, JSON.

What’s Next

Congratulations on completing this Axios Getting Started tutorial! Here’s where to go from here:

  • Practice daily — Consistency is more important than long study sessions
  • Build a project — Apply what you learned by building something real
  • Explore related topics — Check out other tutorials in the same category
  • Join the community — Discuss with other learners and share your progress

Remember: every expert was once a beginner. Keep coding!

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro