Our react app is using window.fetch method for the http calls in most or all of its areas. Before, it had only one token for accessing the content, and what we did is that, we added a header with every request individually, to send the token etc. Below is the sample code of such request:
useEffect(() => {
// GET S3 CREDANTIONS
fetch("/dashboard/de/question/s3credentials", {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${loginReducer}`,
},
})
But now we have configured our api to access two tokens, one for accessing content, the other for refreshing the access token. And for that, after searching from internet, we decided to add an axios interceptor, to check if the access_token is valid, before each http call. So, I made the interceptor and put it inside the index.js of the react app. to check globally for every http request before sending it, if the access_token is valid; and refresh if it is not. I got this idea from this link: https://blog.bitsrc.io/setting-up-axios-interceptors-for-all-http-calls-in-an-application-71bc2c636e4e Other than this link, I studied it from many other websites including stackoverflow, and I understood this more so applied it. Below is the axios interceptor's code in the index.js file (as a whole):
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import axios from "axios";
import AdminIndex from "./AdminPanel/Pages/AdminIndex";
import Cookies from "js-cookie";
// React Redux
import allReducers from "./reducers/index";
import { createStore } from "redux";
import { Provider } from "react-redux";
import StateLoader from "./reducers/PresistedState";
const stateLoader = new StateLoader();
let store = createStore(
allReducers,
stateLoader.loadState(),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
axios.interceptors.request.use(
async (config) => {
let serverCallUrl = new URL(config.url);
if (serverCallUrl.pathname.includes("/superuser/login")) return config;
let access_token = Cookies.get("access");
let refresh_token = localStorage.getItem("refresh_token");
await AdminIndex.hasAccess(access_token, refresh_token);
return config;
},
(error) => {
return Promise.reject(error);
}
);
store.subscribe(() => {
stateLoader.saveState(store.getState());
});
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
there is some problem with the axios interceptor I think. Because when I start the app and enter the login credentials, the app says wrong username and password etc.. I wonder if the problem is because our app is using the fetch method instead of axios? Because we are trying to implement axios interceptor for the fetch http calls. And just for the login code, we have applied axios to authenticate the user. Below is the handleSubmit function of login:
const handleSubmit = async (e) => {
e.preventDefault();
axios({
method: "post",
url: "/superuser/login",
headers: {
"content-type": "application/x-www-form-urlencoded;charset=utf-8",
},
data: `username=${values.username}&useremail=${values.useremail}`,
})
.then((res) => {
const { access_token, refresh_token } = res.data;
Cookies.set("access", access_token);
localStorage.setItem("refresh_token", refresh_token);
props.set_login(res.data.access_token);
history.push("/admin/panel/papers");
})
.catch((err) => setDialogStatus(true));
};
Please have a look what is causing the error to not being able to log in the app. If I remove the interceptor, the app logs in successfully, but then I won't be able to refresh the access_token when it expires. In the interceptor, I have put the function to refresh the access_token and store it again in the props of app. Hopefully I have clearly stated my issue. But still if something is missing, please don't block the question just add a comment and I will immediately respond to it. Thank you in advance!
No! axios interceptors is the internal mechanism of axios; which means, it only intercepts the requests that are sent by the axios library itself. If we want to intercept the window.fetch requests, we'll need to setup custom interceptors for that, for example filtering in the catch block if the response from api is a 403 error, then perform specific action. But even still, the most preferred approach is to just use the axios library totally and be replaced all over the project.