I am using Axios to send requests to the server. This is the instance I use:
export default axios.create({
baseURL: "https://wagal.com",
headers: {
"Content-Type": "application/json; charset=utf-8",
"Authorization": `Bearer ${store.getState().auth.userData.token}`,
},
});
and here is how I use above instance to enable and disable 2fa:
function switchTfa(data) {
if (data) {
return (dispatch) => {
return api_request
.post("/api/user/tfa/enable", {})
.then((response) => {
dispatch(isLoading(false));
dispatch(
userData({
tfa_enabled: data,
user_token: store.getState().auth.userData.token,
})
);
console.log("Success");
})
.catch((error) => {
dispatch(isLoading(false));
console.log(`error.message`, error.message);
});
};
} else {
return (dispatch) => {
dispatch(isLoading(true));
return api_request
.post("/web-api/user/tfa/disable", {})
.then((response) => {
dispatch(isLoading(false));
dispatch(
userData({
tfa_enabled: data,
user_token: store.getState().auth.userData.token,
})
);
console.log("Success");
})
.catch((error) => {
dispatch(isLoading(false));
console.log(`error.message`, error.message);
});
};
}
}
Now, if I send this request, I get below error:
Request failed with status code 400
If I unquote "Authorization" in Axios instance it works
export default axios.create({
baseURL: "https://wagal.com",
headers: {
"Content-Type": "application/json; charset=utf-8",
Authorization: `Bearer ${store.getState().auth.userData.token}`,
},
});
Now, if I reload the app and send the request, it throws this 400 error, but if I wrap "Authorization" with quote again, it sends the request, weird!!!
Why after every reloads I get 400 errors sometimes by quoting and sometimes by unquoting "Authorization"?
Thank you
This is because the store is not persistent. As I can imagine from your code that state is not maintained globally such as Redux, hence when you refresh then the store is empty. Ideally when we want access token to be sent for API call then you will have two options,
You can read about more here : https://auth0.com/docs/security/data-security/token-storage#browser-in-memory-scenarios