Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Using Axios Interceptors | Handling Responses and Advanced Axios Features
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

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 2. Hoofdstuk 3

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Suggested prompts:

Can you show me how to set up a response interceptor for error handling?

What are some best practices for using Axios interceptors in React?

How do I remove or disable an interceptor if I no longer need it?

bookUsing Axios Interceptors

Veeg om het menu te tonen

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

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 2. Hoofdstuk 3
some-alt