Axios Getting Started — Complete Beginner's Guide to HTTP Requests
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.
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
| Feature | What it means for you |
|---|---|
| Auto JSON parsing | JSON responses are automatically converted to JavaScript objects |
| Error handling | Non-2xx responses throw errors you can catch |
| Timeouts | Built-in timeout config — no extra code needed |
| Interceptors | Run code before every request or after every response |
| Cancellation | Cancel in-flight requests when the user navigates away |
| Works everywhere | Same 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 axiosimport 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: 200What’s happening step by step:
axios.get()sends an HTTP GET request to the URL- The server processes the request and sends back a JSON response
- Axios automatically parses the JSON into a JavaScript object
- The parsed data is available at
response.data
The Four Main HTTP Methods
| Method | What it does | Analogy |
|---|---|---|
| GET | Retrieve data | Looking at a menu |
| POST | Create new data | Adding a new item to the menu |
| PUT | Replace existing data | Changing an entire menu item |
| DELETE | Remove data | Removing 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:
error.responseexists — The server responded but with an error code (4xx or 5xx). You can checkerror.response.statusanderror.response.data.error.requestexists but noerror.response— The request was sent but never received a response. This happens with network failures, timeouts, or the server being down.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
| Feature | Axios | Fetch API |
|---|---|---|
| JSON parsing | Automatic | Manual (response.json()) |
| Error on 4xx/5xx | Yes (throws) | No (only network errors) |
| Timeout | Built-in timeout option | Manual via AbortSignal |
| Request cancellation | Built-in | Manual AbortController |
| Upload progress | onUploadProgress | Complex (via streams) |
| Interceptors | Yes | Not available |
| Bundle size | ~14KB gzipped | 0KB (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
What does
response.datacontain? The response body, automatically parsed from JSON into a JavaScript object.How does Axios handle non-2xx HTTP status codes? It throws an error. You catch it in a
try/catchblock and checkerror.response.status.What’s the difference between
error.responseanderror.request?error.responseexists when the server responded (but with an error code).error.requestexists when the request was sent but no response was received (network failure).What does the
{ data }destructuring syntax do? It extracts thedataproperty from the response object directly, saving you from writingresponse.data.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
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
| Tutorial | What You’ll Learn |
|---|---|
| Requests, Responses & Config | Custom config, defaults, instances |
| Interceptors & Error Handling | Auth tokens, logging, retry logic |
| Axios Advanced | Cancellation, 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