interceptor code example
Example 1: angularjs interceptor
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
'request': function(config) {
return config;
},
'requestError': function(rejection) {
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
'response': function(response) {
return response;
},
'responseError': function(rejection) {
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
return {
'request': function(config) {
},
'response': function(response) {
}
};
});
Example 2: interceptors
const api = axios.create({
baseURL: '/',
headers: {
'Content-Type': 'application/json'
},
})
api.interceptors.request.use(
config => {
const token = localStorage.getItem('token')
if (token) {
config.headers['Authorization'] = `Token ${token}`
}
return config
},
error => Promise.reject(error)
)
export default api