Upon sending a request, we'll receive either a success response or an error response. In axios
, the success response is handled in the then
block, and the error is handled inside the catch
block.
Using
Interceptors
, we can intercept the requests or responses before they are handled by thethen
orcatch
block.
axios
We can use the Interceptors
to intercept the response before the then
block handles the response.
Read this Answer to learn about
axios
.
const interceptor = axios.interceptors.response.use(successFn, errorFn);
When adding an interceptor to the response we need to pass two functions as an argument as follows:
successFunction
– This function is triggered if the status code comes under 2xx
. We need to return the response object from this function.
errorFunction
– This function is triggered if the status code is outside the range of 2xx
.
We will get the interceptor instance as a return value which can be used to remove the interceptors later.
Let's write an example to use the Interceptors
. Here we will load the dummy user data from JSONPlaceHolder website. Inside Interceptors
we will modify the structure of the received user data.
Let's discuss the code above:
Line 6: Include the axios
library.
Lines 10–19: Create a function cleanData
that will take the user's data as an argument and return an array of user data. The returned user object will only contain the name and email.
Lines 23–30: Add the interceptors for the response
. Inside the success callback function, invoke the cleanData
function with response data as an argument. The data returned from the cleanData
function is set as the data
of the response object.
Lines 32–35: Make a GET
request to get the user's data. Once the server returns the response the interceptors will intercept the response after that the then
block will be executed.
Free Resources