I am an experienced web developer with an eye for a solid UI/UX design. I have specialized in front-end development, responsive web design, modern web frameworks, and Content Management Systems. I also have experience in mobile apps development and back-end coding with PHP, Node.js, and Java. So I am a Full Stackish web developer with a strong passion for a beautiful front-end.
Published on March 26, 2019. Modified on July 12, 2019.
This is a short example of how to catch all Axios HTTP requests, responses, and errors. Catching is implemented with the Axios feature called interceptors. It's possible to catch all requests before they are sent and modify them. Also, responses and errors can be caught globally. For example, interceptors are useful when you want to modify request headers before a request is sent or you are implementing some kind of global error handling system.
Of course, for real use case, it might be too general to handle all requests and responses in the same way. That’s why we will also have a configuration option for each HTTP requests to disable global handling.
In the demo, I have used VanillaToasts library to show a notification when a HTTP request is done.
Embedded content: https://codepen.io/teroauralinna/pen/vPvKWe
Start by installing Axios by the instructions.
Create a new instance and add any global config options you might need to use.
const axiosInstance = axios.create({
baseURL: 'https://...'
})
Add isHandlerEnabled
function which will check if the global handler should be used or not. Here it's also possible to implement additional custom logic. For example, enabling the handler only for the certain HTTP response codes.
const isHandlerEnabled = (config={}) => {
return config.hasOwnProperty('handlerEnabled') && !config.handlerEnabled ?
false : true
}
Now we are later able to disable handler for an individual HTTP call if we want to.
await axiosInstance.get('/v2/api-endpoint', { handlerEnabled: false })
One common use case for a request handler is to modify or add new HTTP headers. For example, an authentication token could be injected into all requests.
const requestHandler = (request) => {
if (isHandlerEnabled(request)) {
// Modify request here
request.headers['X-CodePen'] = 'https://codepen.io/teroauralinna/full/vPvKWe'
}
return request
}
axiosInstance.interceptors.request.use(
request => requestHandler(request)
)
const errorHandler = (error) => {
if (isHandlerEnabled(error.config)) {
// Handle errors
}
return Promise.reject({ ...error })
}
const successHandler = (response) => {
if (isHandlerEnabled(response.config)) {
// Handle responses
}
return response
}
axiosInstance.interceptors.response.use(
response => successHandler(response),
error => errorHandler(error)
)
And now every request made by Axios uses the handlers we have defined.
24.10.2019
12.06.2019
02.12.2018
10.11.2018
02.05.2018
04.04.2018
28.03.2018
05.03.2018
25.10.2019
07.08.2019
10.07.2019
11.06.2019
09.06.2019
23.03.2019
23.03.2019
09.12.2018