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

How to implement a " before " callback in axios

1个答案

1

When using Axios for HTTP requests, implementing a 'before' callback enables us to perform specific operations before sending the request, such as setting request headers, logging, and validating parameters. Axios itself provides a mechanism called interceptors, which can be used to implement the 'before' callback functionality.

Axios Interceptors

Interceptors allow us to execute code before the request is sent (request interceptor) and after the response is returned (response interceptor).

Setting Up Request Interceptors

Here are the steps to set up a request interceptor:

  1. Import the Axios module.
  2. Register a request interceptor using the axios.interceptors.request.use method.
  3. Inside this method, you can perform the necessary 'before' operations.

Example Code:

javascript
import axios from 'axios'; // Add a request interceptor axios.interceptors.request.use(function (config) { // Perform actions before sending the request console.log('About to send request, time:', Date.now()); config.headers['Authorization'] = 'Bearer your-token-here'; // Example: Dynamically set request headers // You can conditionally modify the config or directly return an error if (!config.url.includes('api')) { return Promise.reject('Invalid API URL'); } return config; // Must return the config }, function (error) { // Handle request errors return Promise.reject(error); }); // Then we can use Axios normally elsewhere in the application to send requests axios.get('/user?ID=12345') .then(function (response) { console.log('Response data:', response); }) .catch(function (error) { console.log('Error occurred:', error); });

Explanation

  1. Import Axios: First, import the Axios library.
  2. Setting Up Request Interceptors:
    • Before sending the request, interceptors can manipulate the config object, such as adding request headers, checking or modifying the request URL, etc.
    • Interceptors can return the modified config object or interrupt the request by returning Promise.reject(error) when issues are found.
  3. Error Handling: If there are errors during the request configuration phase, these errors can be handled in the second function parameter of the interceptor.

This method is very flexible and allows you to implement various custom logic and validations before the request is actually sent.

2024年6月29日 12:07 回复

你的答案