We use cookies to understand how the site is used and to display ads. Analytics and advertising only run after you accept. You can change your choice anytime. Privacy policy

Skip to content
devvkit
$devvkit learn --librarie axios-guide

Axios Guide

[http][api][networking]
JavaScript / TypeScript
Install
npm install axios

Axios wraps XMLHttpRequest and Node's http module with a consistent Promise-based API.

Interceptors let you add auth tokens or handle 401 redirects globally.

Request cancellation via AbortController prevents state updates on unmounted components.

Basic Usage

GET· Fetch data.
const { data } = await axios.get('/api/users');
POST· Send data.
const { data } = await axios.post('/api/users', { name: 'Alice', email: 'a@b.com' });
Concurrent· Parallel requests.
const [users, posts] = await Promise.all([axios.get('/api/users'), axios.get('/api/posts')]);
Config object· Full config instead of chain.
const { data } = await axios({ method: 'GET', url: '/api/users', params: { page: 1 }, timeout: 5000 });

Interceptors

Request interceptor· Add auth token.
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) config.headers.Authorization = 'Bearer ' + token;
  return config;
});
Response interceptor· Handle 401.
axios.interceptors.response.use(res => res, error => {
  if (error.response?.status === 401) window.location.href = '/login';
  return Promise.reject(error);
});

Error Handling

Error handling· Differentiate errors.
try { await axios.get('/api/users'); }
catch (error) {
  if (axios.isAxiosError(error)) console.error('HTTP:', error.response?.status);
  else console.error('Network:', error);
}

Cancellation

Cancel request· AbortController.
const controller = new AbortController();
axios.get('/api/users', { signal: controller.signal });
controller.abort();

Instances

Axios instance· Pre-configured instance.
const api = axios.create({ baseURL: 'https://api.example.com', timeout: 10000 });
const { data } = await api.get('/users');