Skip to content

Instantly share code, notes, and snippets.

@microideation
Created November 27, 2021 10:16
Show Gist options
  • Save microideation/650e4c4168b2e42c80782dccd97e2eb1 to your computer and use it in GitHub Desktop.
Save microideation/650e4c4168b2e42c80782dccd97e2eb1 to your computer and use it in GitHub Desktop.
import axios from 'axios';
// Define the constants
export const BASE_URL = "http://develop.microideation.local:8080/gateway/";
export const URL_USER_AUTHENTICATE= "api/web/authenticate";
export const URL_REFRESH_TOKEN="api/web/refresh_token";
// Define the miAPI as axios
const miAPI = axios.create({
baseURL: BASE_URL,
withCredentials:true
});
// Add the interceptor for the response to handle the authentication issues
// This interceptor will check if the response status is 401 and will store the
// current request. On 401, it will call the refresh token API and try to restore
// the token. On success, we will post the original request again.
miAPI.interceptors.response.use(function(response) {
// For success return the response as is
return response;
},function(error) {
// Log the error
console.log("error :" + JSON.stringify(error));
// Store the original request
const originalReq = error.config;
// Check if the response is having error code as 401
// and is not a retry (to avoid infinite retries) and
// avoid checking on the authenticate URL as it may be due to user
// entering wrong password.
if ( error.response.status == 401 &&
!originalReq._retry &&
error.response.config.url != URL_USER_AUTHENTICATE ) {
// Set the retry flag to true
originalReq._retry = true;
// Call the refresh_token API
return axios.post(BASE_URL+URL_REFRESH_TOKEN,{})
.then((res) =>{
// If the response is success , then log
if ( res.data.status == "success") {
// Log the message
console.log("token refreshed");
// Return the original request. ie. retry
return axios(originalReq);
}
}).catch((error) => {window.location.href="/logout/nosession"});
}
// Log
console.log("Rest promise error");
// If not matched , then return the error
return Promise.reject(error);
});
export {miAPI};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment