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:
- Import the Axios module.
- Register a request interceptor using the
axios.interceptors.request.usemethod. - Inside this method, you can perform the necessary 'before' operations.
Example Code:
javascriptimport 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
- Import Axios: First, import the Axios library.
- Setting Up Request Interceptors:
- Before sending the request, interceptors can manipulate the
configobject, such as adding request headers, checking or modifying the request URL, etc. - Interceptors can return the modified
configobject or interrupt the request by returningPromise.reject(error)when issues are found.
- Before sending the request, interceptors can manipulate the
- 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 回复