10 Axios Interview Questions and Answers
Prepare for your next web development interview with this guide on Axios, featuring common questions and answers to enhance your skills.
Prepare for your next web development interview with this guide on Axios, featuring common questions and answers to enhance your skills.
Axios is a popular JavaScript library used for making HTTP requests from both the browser and Node.js environments. Known for its simplicity and ease of use, Axios provides a powerful and flexible API for handling asynchronous operations, making it a preferred choice for developers working on web applications and APIs. Its ability to handle requests and responses with ease, along with built-in support for interceptors and automatic JSON data transformation, makes it an essential tool in modern web development.
This article offers a curated selection of interview questions focused on Axios, designed to help you demonstrate your proficiency and understanding of this essential library. By familiarizing yourself with these questions and their answers, you will be better prepared to showcase your technical skills and problem-solving abilities in your upcoming interviews.
To make a simple GET request using Axios to fetch data from ‘https://api.example.com/data’ and log the response, use the following code snippet:
const axios = require('axios'); axios.get('https://api.example.com/data') .then(response => { console.log(response.data); }) .catch(error => { console.error('Error fetching data:', error); });
Interceptors in Axios allow you to modify requests or responses before they are handled. They are useful for adding custom headers, handling errors, and more.
To add a custom header to every request and log every response, use request and response interceptors:
import axios from 'axios'; // Add a request interceptor axios.interceptors.request.use( function (config) { config.headers['Custom-Header'] = 'CustomHeaderValue'; return config; }, function (error) { return Promise.reject(error); } ); // Add a response interceptor axios.interceptors.response.use( function (response) { console.log(response); return response; }, function (error) { return Promise.reject(error); } ); // Example request axios.get('https://api.example.com/data') .then(response => { console.log('Data:', response.data); }) .catch(error => { console.error('Error:', error); });
Cancel tokens in Axios are used to cancel ongoing HTTP requests. This is useful when a request is no longer needed, such as when a user navigates away from a page.
To use cancel tokens, create a cancel token using the CancelToken.source
method and pass it to the Axios request configuration. You can then call the cancel
method on the token to cancel the request.
Example:
const axios = require('axios'); const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).then(function (response) { console.log(response); }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); // Cancel the request source.cancel('Operation canceled by the user.');
To make two concurrent GET requests and log both responses once they are completed, use axios.all
or Promise.all
. This approach allows you to handle multiple asynchronous operations concurrently.
const axios = require('axios'); const requestOne = axios.get('https://api.example.com/endpoint1'); const requestTwo = axios.get('https://api.example.com/endpoint2'); axios.all([requestOne, requestTwo]) .then(axios.spread((responseOne, responseTwo) => { console.log('Response from endpoint 1:', responseOne.data); console.log('Response from endpoint 2:', responseTwo.data); })) .catch(error => { console.error('Error in one of the requests:', error); });
Creating a custom Axios instance allows you to set default configurations, such as a base URL and timeout, which can be reused across multiple requests.
To create a custom Axios instance with a base URL of 'https://api.example.com'
and a timeout of 1000ms, use the axios.create
method:
const axios = require('axios'); const customAxios = axios.create({ baseURL: 'https://api.example.com', timeout: 1000, }); // Example usage customAxios.get('/endpoint') .then(response => { console.log(response.data); }) .catch(error => { console.error('Error:', error); });
To set a default header for all Axios requests, use the defaults
property of the Axios instance. This is useful for setting headers like authentication tokens or content types.
Example:
const axios = require('axios'); // Set default header axios.defaults.headers.common['Authorization'] = 'Bearer YOUR_TOKEN_HERE'; // Now every request will include the Authorization header axios.get('https://api.example.com/data') .then(response => { console.log(response.data); }) .catch(error => { console.error('Error fetching data:', error); });
Retry logic automatically reattempts a failed request. In Axios, this can be achieved using interceptors.
Here is an example of how to implement retry logic:
const axios = require('axios'); const axiosInstance = axios.create(); axiosInstance.interceptors.response.use(null, async (error) => { const { config } = error; if (!config || !config.retry) return Promise.reject(error); config.__retryCount = config.__retryCount || 0; if (config.__retryCount >= config.retry) { return Promise.reject(error); } config.__retryCount += 1; const delay = new Promise((resolve) => setTimeout(resolve, config.retryDelay || 1000)); await delay; return axiosInstance(config); }); const requestConfig = { method: 'get', url: 'https://example.com', retry: 3, retryDelay: 1000, }; axiosInstance(requestConfig) .then(response => console.log(response.data)) .catch(error => console.error('Request failed:', error));
To track the progress of a file upload using Axios, use the onUploadProgress
option. This allows you to monitor the progress of the upload by providing a callback function that receives progress events.
Example:
const axios = require('axios'); const FormData = require('form-data'); const fs = require('fs'); const form = new FormData(); form.append('file', fs.createReadStream('path/to/your/file')); axios.post('https://example.com/upload', form, { headers: form.getHeaders(), onUploadProgress: (progressEvent) => { const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total); console.log(`Upload Progress: ${percentCompleted}%`); } }) .then(response => { console.log('File uploaded successfully:', response.data); }) .catch(error => { console.error('Error uploading file:', error); });
Handling authentication tokens in Axios requests involves configuring Axios to include the token in the headers of each request. This can be achieved using Axios interceptors.
Example:
import axios from 'axios'; // Create an instance of Axios const apiClient = axios.create({ baseURL: 'https://api.example.com', timeout: 1000, }); // Add a request interceptor apiClient.interceptors.request.use( config => { const token = localStorage.getItem('authToken'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }, error => { return Promise.reject(error); } ); export default apiClient;
Axios can be used with both Promises and async/await syntax to handle asynchronous operations.
Using Promises:
const axios = require('axios'); axios.get('https://api.example.com/data') .then(response => { console.log(response.data); }) .catch(error => { console.error('Error fetching data:', error); });
Using async/await:
const axios = require('axios'); async function fetchData() { try { const response = await axios.get('https://api.example.com/data'); console.log(response.data); } catch (error) { console.error('Error fetching data:', error); } } fetchData();