Unleashing Powerful Axios Features

Axios is a JavaScript library for handling HTTP requests, offering features that can enhance your development projects.


This content originally appeared on Telerik Blogs and was authored by Ezekiel Lawson

Axios is a JavaScript library for handling HTTP requests, offering features that can enhance your development projects.

Axios, a JavaScript library for HTTP requests, lets you easily define interceptors to automate specific tasks. Axios has an array of features that can significantly elevate development projects. However, some developers are unaware of these features as more commonly used methods often overshadow them. Most of these features have little to no information, so I’m creating an article to explain these features.

This article aims to shed light on these advanced Axios features, explaining what they are, how they work and when to use them. With this knowledge, you can confidently employ these features in your subsequent development when needed.

Custom Instance

The custom instance involves creating a new file and importing Axios instead of using the default. You can employ axios.create and then pass the objects, enabling the creation of multiple Axios instances, each with its unique set of default configurations such as base URLs, timeout and headers.

const createNewInstance = axios.create({
  baseURL: 'https://api.example.com', 
  timeout: 5000, 
  headers: {
    'Content-Type': 'application/json', 
    'X-Custom-Header': 'value',
  }
});
customAxios.get('/api/data')
  .then(response => {
    console.log('Response:', response.data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

This feature is necessary when your application needs to interact with multiple APIs, each requiring its distinct set of request options. For example, if you intend to create two Axios instances, direct the first to fetch specific data and the second to fetch different data, with individual timeouts set at 2000 ms and 5000 ms, respectively.

Interceptors

Interceptors play a crucial role in the Axios library, as they are methods executed both before a request is sent and after a response is received. These methods are instrumental for performing essential tasks like modifying headers, transforming data or globally handling errors.

Axios comprises two types of interceptors: Request and Response. The request interceptor is invoked before the actual call to the endpoint, allowing adjustments to the request configuration. On the other hand, the response interceptor is triggered before the promise is fulfilled, ensuring that modifications can be made before the callback receives the data.

Request interceptor:

customAxios.interceptors.request.use(config => {
  console.log('Request Interceptor:', config);
  return config;
}, error => {
  return Promise.reject(error);
});

Response interceptor:

customAxios.interceptors.response.use(response => {
  console.log('Response Interceptor:', response);
  return response;
}, error => {
   return Promise.reject(error);
});

Interceptors prove to be beneficial in the context of API calls, serving the purpose of applying logic either before or after the execution of the API call. Some notable use cases include:

  • Logging requests and responses for debugging purposes.
  • Adding global headers or applying authorization headers to all requests.
  • Implementing global error handling for all requests.
  • Displaying loading indicators during API requests.
  • Implementing request cancellation, especially in scenarios like navigating away from a page.

Cancel Request

Before version v0.22.0, canceling requests with Axios was not directly supported. Axios offers two methods for canceling requests: cancelToken and signal(AbortController). While the cancelToken has been deprecated, the recommended method for cancellation is using the signal(AbortController). The AbortController is a JavaScript controller object that allows you to abort web requests as needed, and it is supported by all browsers and other HTTP clients.

Here is an example of how you can cancel a request with the cancelToken:

const cancelTokenSource = axios.CancelToken.source();
customAxios.get('/api/data', {
  cancelToken: cancelTokenSource.token
})
  .then(response => {
    console.log('Response:', response.data);
  })
  .catch(error => {
    if (axios.isCancel(error)) {
      console.log('Request canceled:', error.message);
    } else {
      console.error('Error:', error);
    }
  });
cancelTokenSource.cancel('Request canceled by the user');

Here is an example of how you can cancel a request with the AbortController:

const controller = new AbortController();
axios.get('/foo/bar', { signal: controller.signal })
  .then(response => {
    // Handle the response
    console.log('Response:', response.data);
  })
  .catch(error => {
    if (error.name === 'AbortError') {
      // Handle cancellation
      console.log('Request was canceled:', error.message);
    } else {
      // Handle other errors
      console.error('Error:', error);
    }
  });
// This function will cancel the request 
controller.abort();

Canceling requests is needed to manage and control asynchronous tasks’ lifecycles, particularly when working with components.

URLSearchParams

URLSearchParams is utilized for working with query parameters in a URL. It proves useful when you need to manipulate or extract information from the query parameters of a URL. For instance, you can use URLSearchParams to include query parameters in a Fetch API request, prepare form data to be sent in a POST request, or update and add new query parameters to an existing URL—as seen in the code below:

const url = new URL('https://example.com/api/data?key1=value1&key2=value2');
url.searchParams.set('key1', 'new_value1');
url.searchParams.append('key3', 'value3');

console.log(url.toString());

A URL object is created in the code snippet above, representing a URL with initial query parameters. The value of an existing parameter key1 is then updated, and a new parameter key3 is added. Printing the modified URL using console.log will yield the following output for the updated URL:

'https://example.com/api/data?key1=new_value1&key2=value2&key3=value3'

Defenses Against XSRF Attack

Axios incorporates a built-in mechanism for XSRF headers, fortifying defenses against Cross-Site Request Forgery (XSRF) attacks. Utilizing XSRF tokens, these unpredictable and unique values are generated by the application and transmitted to the client. Included in HTTP requests, these tokens undergo server verification to confirm the legitimacy of the request, blocking unauthorized actions. Implementing the XSRF token in Axios better safeguards against attacks and improves the security of your application.

You can easily implement XSRF protection features when:

  • Building a web application that involves user authentication and interaction.
  • Configuring specific XSRF headers for enhanced security.
  • Consuming an API that mandates XSRF protection for secure interactions.

Conclusion

Axios is a handy JavaScript library for handling HTTP requests, offering features that can enhance your development projects. This article has explained these features by providing clarity of what they are, how they operate and when to apply them. With this understanding, you can easily integrate these features into your development work when needed.


This content originally appeared on Telerik Blogs and was authored by Ezekiel Lawson


Print Share Comment Cite Upload Translate Updates
APA

Ezekiel Lawson | Sciencx (2024-07-24T08:27:22+00:00) Unleashing Powerful Axios Features. Retrieved from https://www.scien.cx/2024/07/24/unleashing-powerful-axios-features/

MLA
" » Unleashing Powerful Axios Features." Ezekiel Lawson | Sciencx - Wednesday July 24, 2024, https://www.scien.cx/2024/07/24/unleashing-powerful-axios-features/
HARVARD
Ezekiel Lawson | Sciencx Wednesday July 24, 2024 » Unleashing Powerful Axios Features., viewed ,<https://www.scien.cx/2024/07/24/unleashing-powerful-axios-features/>
VANCOUVER
Ezekiel Lawson | Sciencx - » Unleashing Powerful Axios Features. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/24/unleashing-powerful-axios-features/
CHICAGO
" » Unleashing Powerful Axios Features." Ezekiel Lawson | Sciencx - Accessed . https://www.scien.cx/2024/07/24/unleashing-powerful-axios-features/
IEEE
" » Unleashing Powerful Axios Features." Ezekiel Lawson | Sciencx [Online]. Available: https://www.scien.cx/2024/07/24/unleashing-powerful-axios-features/. [Accessed: ]
rf:citation
» Unleashing Powerful Axios Features | Ezekiel Lawson | Sciencx | https://www.scien.cx/2024/07/24/unleashing-powerful-axios-features/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.