APIviz Home

01 — GETTING STARTED

What is Axios?

Axios is a promise-based HTTP client for the browser and Node.js. It provides a simple, clean API for making HTTP requests with powerful features built in.

The Data Journey — Click to Animate

React App

UI Layer

Axios

HTTP Client

Express API

Backend

MongoDB

Database

Auto JSON

No more JSON.parse/stringify. Axios handles it automatically.

XSRF Protection

Built-in cross-site request forgery protection out of the box.

Universal

Same API in browser and Node.js. Write once, run everywhere.

More Features

  • Promise-based — async/await friendly
  • Request & response interceptors
  • Automatic request timeout
  • Cancel requests with AbortController
  • Parallel requests with axios.all
  • Response status validation

First Look — 3 Lines

React ComponentGET Example
import axios from 'axios'; const { data } = await axios.get('/api/users'); // data is already a JavaScript object!

02 — GETTING STARTED

Axios vs Fetch

Both make HTTP requests. But Axios eliminates boilerplate and edge-case headaches. See the difference side by side.

WINNER: AXIOS

JSON Parsing

Fetch

const res = await fetch('/api/users'); const data = await res.json(); // Must call .json() manually

Axios

const { data } = await axios.get('/api/users'); // Auto-parsed! data is an object
WINNER: AXIOS

Error Handling

Fetch

const res = await fetch(url); if (!res.ok) throw new Error(res.status); // 404/500 need manual check

Axios

try { const { data } = await axios.get(url); } catch (err) { // ALL errors land here — unified }
TIE

POST Body

Fetch

await fetch(url, { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({name:'Alice'}) });

Axios

await axios.post(url, { name: 'Alice' }); // Auto-stringifies + sets header

03 — GETTING STARTED

Installation

Add Axios to your project in seconds.

npm

$ npm install axios

yarn

$ yarn add axios

CDN

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

ES Module

import axios from 'axios';

04 — CORE REQUESTS

GET Requests

Retrieve data from a server. Axios makes it clean with query params, config options, and auto-parsed JSON.

BASIC

Simple GET

const response = await axios.get('/api/users'); const users = response.data; // Auto-parsed JSON
PARAMS

GET with Query Parameters

axios.get('/api/users', { params: { page: 1, limit: 10, sort: 'name' } }); // → GET /api/users?page=1&limit=10&sort=name
REACT

GET in React Component

function UserList() { const [users, setUsers] = useState([]); useEffect(() => { axios.get('/api/users') .then(res => setUsers(res.data)) .catch(err => console.error(err)); }, []); return users.map(u => <div>{u.name}</div>); }

05 — CORE REQUESTS

POST Requests

Send data to create resources. Axios auto-stringifies objects and sets Content-Type.

BASIC

Simple POST

const res = await axios.post('/api/users', { name: 'Alice', email: 'alice@example.com' }); console.log(res.data); // { id: 42, name: 'Alice', ... } console.log(res.status); // 201
REACT FORM

POST from a React Form

const handleSubmit = async (e) => { e.preventDefault(); try { const res = await axios.post('/api/users', form); alert(`Created user #${res.data.id}`); } catch (err) { if (err.response?.status === 409) alert('Email exists'); } };

06 — CORE REQUESTS

PUT / PATCH / DELETE

Same pattern — just change the method.

PUT — Full Replace

await axios.put('/api/users/42', { name: 'Alice Updated', email: 'alice@new.com', role: 'admin' });

PATCH — Partial

await axios.patch('/api/users/42', { role: 'admin' });

DELETE — Remove

await axios.delete('/api/users/42'); // Returns 200 or 204

07 — CORE REQUESTS

Response Object

Axios gives you a rich response object with data, status, headers, and config.

What Axios Returns
{ data: { ... }, // Parsed body status: 200, // HTTP status statusText: 'OK', // Status text headers: { ... }, // Response headers config: { ... }, // Request config request: { ... } // XMLHttpRequest }
.data

Parsed response body. Already a JS object for JSON.

.status

HTTP status code (200, 201, 404, etc.)

.headers

Response headers — rate limits, pagination.

.config

The exact config that generated this request.

08 — ADVANCED

Interceptors

Middleware for HTTP requests. Run code before a request is sent and after a response is received.

Interceptor Pipeline — Click to Animate

Your Code

Request
Interceptor

Axios Core

Server

Request Interceptor

axios.interceptors.request.use( (config) => { const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } console.log(`→ ${config.method.toUpperCase()} ${config.url}`); return config; }, (error) => Promise.reject(error) );

Response Interceptor

axios.interceptors.response.use( (response) => { console.log(`← ${response.status}`); return response; }, (error) => { if (error.response?.status === 401) { window.location = '/login'; } return Promise.reject(error); } );

09 — ADVANCED

Axios Instances

Create reusable pre-configured HTTP clients. Each instance has its own defaults, interceptors, and base URL.

Creating an Instance

import axios from 'axios'; const api = axios.create({ baseURL: 'https://api.example.com/v1', timeout: 10000, headers: { 'Content-Type': 'application/json', 'X-App-Version': '2.0.0' } }); // Now use api instead of axios const { data } = await api.get('/users'); // → GET https://api.example.com/v1/users

Multiple Instances — Different Services

const authApi = axios.create({ baseURL: 'https://auth.example.com' }); const dataApi = axios.create({ baseURL: 'https://data.example.com' }); const fileApi = axios.create({ baseURL: 'https://files.example.com', timeout: 30000 }); // Each has its own config and interceptors authApi.interceptors.request.use(addAuthToken); fileApi.interceptors.request.use(addUploadHeaders);

10 — ADVANCED

Error Handling

Axios categorizes errors into three types: response errors (server replied with 4xx/5xx), request errors (no response), and setup errors.

The Three Error Types

try { const res = await axios.get('/api/users'); } catch (error) { if (error.response) { // ❌ Server responded with 4xx/5xx console.log(error.response.status); // 404, 500, etc. console.log(error.response.data); // Error body console.log(error.response.headers); } else if (error.request) { // 🔇 Request sent but no response (network down, CORS) console.log(error.request); } else { // ⚙️ Error setting up the request console.log(error.message); } }

Response Error

Server replied with 4xx or 5xx status. Has .response

Request Error

No response received. Network, CORS, or timeout. Has .request

Setup Error

Bad config or invalid URL. Has .message

11 — ADVANCED

Concurrent Requests

Fire multiple requests at once and wait for all to complete. Use Promise.all with Axios for parallel data fetching.

Promise.all Pattern

const [usersRes, postsRes, settingsRes] = await Promise.all([ axios.get('/api/users'), axios.get('/api/posts'), axios.get('/api/settings') ]); const users = usersRes.data; const posts = postsRes.data; const settings = settingsRes.data;

Promise.allSettled — Partial Failures

const results = await Promise.allSettled([ axios.get('/api/users'), axios.get('/api/broken'), // This might fail ]); results.forEach((r, i) => { if (r.status === 'fulfilled') console.log(r.value.data); else console.error(`Request ${i} failed:`, r.reason); });

12 — FULL STACK

Full-Stack Architecture

How React, Axios, Express, and MongoDB work together in a full-stack application.

The Stack — Click to Animate

React

Port 3000

Axios

HTTP Client

Express

Port 5000

MongoDB

Port 27017

Folder Structure

my-fullstack-app/ ├── client/ ← React (CRA or Vite) │ ├── src/ │ │ ├── api/ ← Axios instances │ │ ├── components/ │ │ └── App.jsx │ └── package.json ├── server/ ← Express + Mongoose │ ├── routes/ │ ├── models/ │ ├── server.js │ └── package.json └── README.md

13 — FULL STACK

Express API

Build the backend that your Axios frontend talks to. Express makes RESTful route handling clean and simple.

Express Server

server.jsExpress
const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); app.use(express.json()); // GET all users app.get('/api/users', async (req, res) => { const users = await User.find(); res.json(users); }); // POST create user app.post('/api/users', async (req, res) => { const user = await User.create(req.body); res.status(201).json(user); }); // PUT update user app.put('/api/users/:id', async (req, res) => { const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true }); res.json(user); }); // DELETE user app.delete('/api/users/:id', async (req, res) => { await User.findByIdAndDelete(req.params.id); res.status(204).end(); }); app.listen(5000, () => console.log('API on :5000'));

14 — FULL STACK

MongoDB + Mongoose

The database layer. Mongoose gives MongoDB an elegant schema and query API.

Mongoose Schema & Model

models/User.jsMongoose
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, role: { type: String, default: 'user', enum: ['user', 'admin', 'editor'] }, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model('User', userSchema);

Connection

const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/myapp') .then(() => console.log('MongoDB connected')) .catch(err => console.error('MongoDB error:', err));

15 — PRACTICE

Axios Playground

Try live API calls using simulated Axios syntax. See the request config and response in real time.

Request Builder

Response

Response Body
// Response will appear here

Quick Try

16 — PRACTICE

Axios Quiz

Test your knowledge. 10 questions covering everything from basics to advanced patterns.

1/10