Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Using Axios Interceptors | Handling Responses and Advanced Axios Features
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Axios for React Applications

bookUsing Axios Interceptors

When building React applications that interact with APIs, you often need to modify requests or handle responses in a consistent way across your app. Axios provides interceptors for this purpose, allowing you to intercept and transform requests or responses globally before they are handled by your components. One common scenario is attaching authentication tokens to every outgoing request so that your API knows who the user is. To set this up, you can use the axios.interceptors.request.use method to add a function that modifies each request before it is sent.

Suppose you store a user's authentication token in local storage after they log in. You want to ensure that every API request includes this token in its headers. Using an Axios request interceptor, you can automatically attach the token to all requests without repeating code in every component. Here is how you might set up such an interceptor in your React app:

import api from "./api";

api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("authToken");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

With this code, before any request is sent, Axios checks if an authToken exists in local storage. If it does, the token is added to the Authorization header. This ensures all outgoing requests include the necessary credentials, reducing the risk of missing authentication and improving security and maintainability.

Interceptors are not limited to handling authentication. Another frequent use case is global error logging. By adding a response interceptor using axios.interceptors.response.use, you can catch and process errors in one place, such as logging them or displaying a notification to the user. This helps you avoid duplicating error handling logic in every component that makes API calls. Interceptors are also useful for handling specific API response codes, such as redirecting users to a login page if a 401 Unauthorized error is received, or standardizing the shape of data returned from the API before it reaches your React components. By centralizing these concerns, Axios interceptors help you keep your codebase organized and reduce repetition.

question mark

Which of the following best describes the role of Axios interceptors in a React application?

Select the correct answer

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 3

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

bookUsing Axios Interceptors

Pyyhkäise näyttääksesi valikon

When building React applications that interact with APIs, you often need to modify requests or handle responses in a consistent way across your app. Axios provides interceptors for this purpose, allowing you to intercept and transform requests or responses globally before they are handled by your components. One common scenario is attaching authentication tokens to every outgoing request so that your API knows who the user is. To set this up, you can use the axios.interceptors.request.use method to add a function that modifies each request before it is sent.

Suppose you store a user's authentication token in local storage after they log in. You want to ensure that every API request includes this token in its headers. Using an Axios request interceptor, you can automatically attach the token to all requests without repeating code in every component. Here is how you might set up such an interceptor in your React app:

import api from "./api";

api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("authToken");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

With this code, before any request is sent, Axios checks if an authToken exists in local storage. If it does, the token is added to the Authorization header. This ensures all outgoing requests include the necessary credentials, reducing the risk of missing authentication and improving security and maintainability.

Interceptors are not limited to handling authentication. Another frequent use case is global error logging. By adding a response interceptor using axios.interceptors.response.use, you can catch and process errors in one place, such as logging them or displaying a notification to the user. This helps you avoid duplicating error handling logic in every component that makes API calls. Interceptors are also useful for handling specific API response codes, such as redirecting users to a login page if a 401 Unauthorized error is received, or standardizing the shape of data returned from the API before it reaches your React components. By centralizing these concerns, Axios interceptors help you keep your codebase organized and reduce repetition.

question mark

Which of the following best describes the role of Axios interceptors in a React application?

Select the correct answer

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 3
some-alt