https://github.com/MrFiniOrg/AxiosQuestion
I would like to have my project setup so that I do not have to specify the same request header in every http call.
Using interceptors, it runs on each request so if the token changes (refreshes) then the next request picks up the new token. Check for existing values in the request to allow overriding of the header. Consider we are using any token generator and updating token in local storage. Here we are using keyclock object that is stored in localStorage
import * as axios from "axios";
axios.defaults.baseURL = process.env.REACT_APP_BASE_URL;
axios.interceptors.request.use(
config => {
if (!config.headers.Authorization) {
const token = JSON.parse(localStorage.getItem("keyCloak")).token;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
}
return config;
},
error => Promise.reject(error)
);