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.
I have searched this online but I have not been able to accomplish this in my project.
Would someone please assist me in resolving this issue I am having. I am new to react and axios and I am not sure how to configure this.
My project seems to be doing this but it is sending the request 2 times. One with the header and one without.
My axios call can be found in the app.js class component
I also had the same issue and solution was to locate them in
index.js
:Also, I use
.env
files to keep for example base urls:.env.production
.env.development
And when you run locally .env.development will be used, for production build (
npm run build
) .env.production will be used..env
: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variablesUsing 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
You can specify config defaults that will be applied to every request.
Global axios defaults
For more specific info, please visit their docs.
UPDATE:
You can do it in two ways:
1. In your
index.js
file [meaning the top-level aka 'root' file] you can configure yourrequest/ response
methods. Something like this:2. Or you can create a new file, a new instance of your
axios.js
file to be precise and import the configurations separately in your components where you might need them. You could name it, egaxiosConfig.js
and put your specific configs inside of it. Something like this:axiosConfig.js
After that you would import this file to components that need it and use it instead of the previous Axios [node_modules] import, like this:
Example.js
NOTE: You can combine these two methods as needed, but remember that the configurations made in your
configAxios.js
file will overwrite those made in yourindex.js
file [if they are the same configurations, that is :) ]