Sobes.tech
Middle

What libraries have you used for sending network requests? How does Axios differ from Fetch? What are interceptors?

sobes.tech AI

Answer from AI

To send network requests in the frontend, libraries like Axios and the built-in Fetch API are often used.

Differences between Axios and Fetch:

  • Axios automatically transforms JSON responses, Fetch requires calling .json().
  • Axios supports request cancellation via CancelToken, which is more complex to implement with Fetch.
  • Axios automatically handles HTTP status errors (e.g., 404), while Fetch considers only network failures as errors.
  • Axios supports interceptors, which are convenient for processing requests and responses.

Interceptors are functions that intercept requests or responses before they are processed in the main code. They are useful for:

  • Adding authorization headers.
  • Logging requests and responses.
  • Global error handling.

Example of using an interceptor in Axios:

import axios from 'axios';

axios.interceptors.request.use(config => {
  config.headers['Authorization'] = 'Bearer token';
  return config;
});

axios.interceptors.response.use(response => {
  // handle successful response
  return response;
}, error => {
  // global error handling
  return Promise.reject(error);
});
What libraries have you used for sending network… - sobes.tech