e11en e11en - 1 month ago 30
React JSX Question

Store api key in react webapp

My react web application uses axios to make an API post request.
The API needs a parameter called token for each post request.

Is there a way to always add the token parameter for each post request I do, so I don't have to add it manually every time, and where to save this token in a secure location?

I feel what I do now is a bit redundant. Example:

axios.post('apiUrl.com', {
token: 'abcdefg12345678',
userId: 1
}).then(() => {//do something});

Answer

Use axios interceptors. If you add a request interceptor, you can make a change (add token) to each request:

axios.interceptors.request.use(function(config) {
    config.data = config.data || {};
    config.data.token = 'abcdefg12345678';
    return config;
});
Comments