乐闻世界logo
搜索文章和话题

How can you use axios interceptors

4个答案

1
2
3
4

Axios interceptors allow us to intercept and modify requests or responses before they are handled by then or catch. Interceptors are commonly used for the following purposes:

  1. Modify request data before sending it to the server.
  2. Attach authentication information (e.g., JWT token) to the request headers before sending the request.
  3. Cancel requests before they reach the server.
  4. Handle all response errors uniformly.
  5. Transform response data before it reaches the application logic.

Using Axios interceptors primarily involves two types: request interceptors and response interceptors.

Adding Request Interceptors

Request interceptors are executed before the request is actually sent. Here is a general method to add a request interceptor:

javascript
// Add request interceptor axios.interceptors.request.use(function (config) { // Do something before sending the request, e.g., set token config.headers.Authorization = `Bearer ${YOUR_AUTH_TOKEN}`; return config; }, function (error) { // Handle request errors return Promise.reject(error); });

Here, we first add a request interceptor using axios.interceptors.request.use. This interceptor receives two functions as parameters. The first function is called before the request is sent and receives the request configuration object config as a parameter, allowing us to modify this configuration. In the example above, we add an Authorization header with a hypothetical authentication token YOUR_AUTH_TOKEN. The second function is executed when a request error occurs; here we simply return the error.

Adding Response Interceptors

Response interceptors are called before the server's response data reaches then or catch. Here is a general method to add a response interceptor:

javascript
// Add response interceptor axios.interceptors.response.use(function (response) { // Do something with the response data // You can process the response data as needed; this is just an example if (response.data && response.data.success) { return response.data.data; } else { // Handle unsuccessful cases here, or reject with an error return Promise.reject('Error with request'); } }, function (error) { // Handle response errors if (error.response.status === 401) { // If status code is 401, you can handle re-authentication, etc. } return Promise.reject(error); });

In this example, we add a response interceptor using axios.interceptors.response.use. It also receives two functions. The first function is called when a successful response is returned and receives the response object response as a parameter. In this function, we perform some simple checks and return only the necessary data part. The second function is called when a response error occurs, for example, you can handle 401 Unauthorized status codes by implementing automatic re-authentication or redirecting to the login page.

Removing Interceptors

If you want to remove an interceptor at some point, you can do the following:

javascript
// Adding an interceptor returns an interceptor ID const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); // Use this ID to remove the interceptor axios.interceptors.request.eject(myInterceptor);

In the above code, we first add a request interceptor and save the returned interceptor ID in the myInterceptor variable. Then, we call the axios.interceptors.request.eject method and pass this ID to remove the interceptor.

2024年6月29日 12:07 回复

It functions as an interceptor, which is applied to any request (GET, POST, PUT, DELETE) or response (from the server) to handle authorization scenarios. See the following example: Axios Interceptors and Asynchronous Login Here's another article on this topic with a different example: Handling Error Responses with Grace Therefore, one key aspect of this example is that you can use interceptors to detect if your authorization token has expired (e.g., when you receive a 403 error) and redirect the page.

2024年6月29日 12:07 回复

For example, if you want to measure the time taken from sending a request to receiving a response, you can use the following code:

javascript
const axios = require("axios"); (async () => { axios.interceptors.request.use( function (request) { request.time = { startTime: new Date() }; return request; }, (error) => { return Promise.reject(error); } ); axios.interceptors.response.use( function (response) { response.config.time.endTime = new Date(); response.duration = response.config.time.endTime - response.config.time.startTime; return response; }, (error) => { return Promise.reject(error); } ); axios .get("http://localhost:3000") .then((response) => { console.log(response.duration) }) .catch((error) => { console.log(error); }); })();
2024年6月29日 12:07 回复

Simply put, it acts like a checkpoint for each HTTP operation. Every API call made passes through this interceptor.

Why are there two interceptors?

API calls consist of two parts: requests and responses. Since it behaves like a checkpoint, requests and responses each have their own interceptors.

Some use cases for request interceptors -

Suppose you want to check if your credentials are valid before sending a request. Therefore, you can verify your credentials at the interceptor level instead of actually making the API call.

Suppose you need to attach a token to each outgoing request instead of repeating the token-adding logic every time you make an Axios call. You can create an interceptor that attaches the token to every outgoing request.

Some use cases for response interceptors -

Suppose you receive a response and determine if the user is logged in based on the API response you want to infer. Therefore, in the response interceptor, you can initialize a class to handle user login status and update it accordingly based on what you receive.

Suppose you've made an API request with valid credentials but lack the appropriate role to access the data. Therefore, you can trigger an alert from the response interceptor indicating the user is unauthorized. This way, you avoid having to handle unauthorized API errors for every Axios request you make.

Here are some code examples

Request Interceptors

  • You can log the Axios configuration object (if needed) by doing the following (in this example, by checking environment variables):

    const DEBUG = process.env.NODE_ENV === "development";

    axios.interceptors.request.use((config) => { /** In dev, intercepts request and logs it into console for dev */ if (DEBUG) { console.info("✉️ ", config); } return config; }, (error) => { if (DEBUG) { console.error("✉️ ", error); } return Promise.reject(error); });

  • If you want to check which headers are being sent or add additional generic headers, you can use the config.headers object. For example:

    axios.interceptors.request.use((config) => { config.headers.genericKey = "someGenericValue"; return config; }, (error) => { return Promise.reject(error); });

  • For a GET request, you can find the sent query parameters in config.params.

Response Interceptors

  • You can even choose to parse the API response at the interceptor level and pass down the parsed response instead of the raw response. If you use the API in multiple places in the same way, it can save you from writing parsing logic repeatedly. One approach is to pass an extra parameter, parse: true, in the request and use it in the response interceptor to perform your operations. For example:

    //Assume we pass an extra parameter "parse: true" axios.get("/city-list", { parse: true });

    Once, in the response interceptor, we can use it like this:

    axios.interceptors.response.use((response) => { if (response.config.parse) { //perform the manipulation here and change the response object } return response; }, (error) => { return Promise.reject(error.message); });

    In this case, the operation is performed as long as parse is present in the response.config object; for other cases, it works as is.

  • You can even check the HTTP status code and make decisions based on it. For example:

    axios.interceptors.response.use((response) => { if(response.status === 401) { alert("You are not authorized"); } return response; }, (error) => { if (error.response && error.response.data) { return Promise.reject(error.response.data); } return Promise.reject(error.message); });

2024年6月29日 12:07 回复

你的答案