Interceptor In Vue JS

This article will teach you how to use Axios Interceptors on your requests and responses. By using Interceptor you can intercept requests or responses before they are handled by then or catch

 

Interceptor:

Interceptors assist us in pre- or post-processing requests, which entails that we may alter the requests before they are submitted to the server or the results that are returned after the request.

Interceptors have a universal definition.

 

Get Started:

Step 1:

Create a new Vue project.

vue create interceptor-ex

 

Step 2:

Install the Axios in your application.

npm install axios

 

Step 3:

Import the Axios in your main.js file.

import Axios from 'axios'; 
//
//
Vue.use(Axios);

 

Step 4:

Add a Request interceptor in main.js.

// Add a request interceptor 
Axios.interceptors.request.use(function (config) 
{ 
  // Do something before a request is sent 
  return config; 
}, 
function (error) { 
  // Do something with request error 
  return Promise.reject(error); 
});

 

Step 5:

Add a Response interceptor in main.js.

// Add a response interceptor 
Axios.interceptors.response.use(function (response) 
{ 
  // Any status code that lies within the range of 2xx cause this function to trigger 
  // Do something with response data 
  return response; 
},
function (error) { 
  // Any status codes that fall outside the range of 2xx cause this function to trigger 
  // Do something with response error 
  return Promise.reject(error); 
});

 

Conclusion:

Developers can call interceptor methods on connected target classes in combination with method invocations or lifecycle events by using interceptors in conjunction with Java EE-managed classes. Logging, auditing, and profiling are frequent applications for interceptors.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories