Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

Axios

What is Axios?

Axios is a popular, Promise-based HTTP client for both the browser and Node.js. It automatically serializes request bodies to JSON, automatically parses JSON responses, and rejects the Promise for HTTP error status codes — fixing one of the most common fetch() gotchas.

Install via npm: npm install axios, or include via CDN:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Axios GET, POST, PUT, DELETE
// GET — params are serialized automatically
axios.get('/api/users', {
  params: { page: 1, limit: 10, active: true }
})
.then(response => {
  // response.data is already parsed JSON
  console.log(response.data);
  console.log(response.status);    // 200
  console.log(response.headers);  // response headers
});

// POST — body is automatically JSON.stringify'd
axios.post('/api/users', {
  name: 'Alice',
  email: 'alice@example.com'
})
.then(res => console.log('Created:', res.data));

// PUT
axios.put('/api/users/1', { name: 'Alice Updated', email: 'alice@example.com' })
  .then(res => console.log('Updated:', res.data));

// DELETE
axios.delete('/api/users/1')
  .then(res => console.log('Deleted, status:', res.status));
Request Config and Error Handling
// Full config object
axios({
  method: 'post',
  url: '/api/login',
  headers: { 'X-Custom-Header': 'value' },
  timeout: 10000,           // 10 seconds
  data: { username: 'alice', password: 'secret' }
})
.then(res => console.log(res.data))
.catch(error => {
  if (error.response) {
    // Server responded with a status outside 2xx
    console.error('HTTP Error:', error.response.status);
    console.error('Data:', error.response.data);
  } else if (error.request) {
    // Request was made but no response received (network error)
    console.error('No response received:', error.request);
  } else {
    // Something went wrong setting up the request
    console.error('Request setup error:', error.message);
  }
});
axios.create() and Interceptors
// Create a reusable Axios instance with defaults
const api = axios.create({
  baseURL: 'https://api.example.com/v1',
  timeout: 8000,
  headers: { 'Accept': 'application/json' }
});

// Request interceptor — runs before every request
api.interceptors.request.use(
  config => {
    // Attach auth token from localStorage
    const token = localStorage.getItem('authToken');
    if (token) config.headers.Authorization = `Bearer ${token}`;
    return config;
  },
  error => Promise.reject(error)
);

// Response interceptor — runs after every response
api.interceptors.response.use(
  response => response, // pass through successful responses
  error => {
    if (error.response?.status === 401) {
      // Token expired — redirect to login
      localStorage.removeItem('authToken');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// Now use the instance — baseURL and interceptors apply automatically
api.get('/users').then(res => console.log(res.data));
api.post('/posts', { title: 'Hello' }).then(res => console.log(res.data));

Axios vs Fetch Comparison

FeatureAxiosfetch()
DependencyExternal library (~14KB)Built-in
Auto JSON stringifyYesManual
Auto JSON parseYes (response.data)Manual (res.json())
HTTP error rejectionYes (4xx/5xx reject)No — must check res.ok
Request cancellationCancelToken / AbortControllerAbortController
InterceptorsBuilt-inNot built-in
Upload progressonUploadProgressNot built-in
Node.js supportYesNode 18+ only
Axios with async/await and Upload Progress
// async/await with Axios
async function createUser(userData) {
  try {
    const { data } = await axios.post('/api/users', userData);
    console.log('New user ID:', data.id);
    return data;
  } catch (error) {
    const msg = error.response?.data?.message || error.message;
    console.error('Create user failed:', msg);
    throw error;
  }
}

// File upload with progress tracking
async function uploadFile(file) {
  const formData = new FormData();
  formData.append('file', file);

  try {
    const { data } = await axios.post('/api/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      onUploadProgress: (progressEvent) => {
        const percent = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
        document.getElementById('progress').style.width = `${percent}%`;
        document.getElementById('progress-text').textContent = `${percent}%`;
      }
    });
    console.log('Uploaded:', data.url);
  } catch (err) {
    console.error('Upload failed:', err.message);
  }
}

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.