Using axios I am trying to set default header auth token for all the request. But its not seeting up by default and for any other api call 'Authorization' is not setting up in header.
this is UseHttp.js which is a common file
import axios from 'axios';
const axiosClient = axios.create({
headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
}
});
const UseHttp = (requestConfig) => {
return axiosClient({
url: requestConfig.url,
method: requestConfig.method || 'GET',
data: requestConfig.body && JSON.stringify(requestConfig.body)
}).then((response) => {
if (response.status == 200) {
return response.data;
} else {
throw new Error(response.data.message);
}
}).then((data) => {
return data.data;
}).catch((error) => {
return error.message;
});
};
export const setAuthHeader = (header) => {
axiosClient.defaults.headers.common['Authorization'] = header;}
export default UseHttp;
After login I am setting the header like this
import {USER} from './Url';
import UseHttp, {setAuthHeader} from './UseHttp';
/* eslint-disable */
export const LoginApi = async (values) => {
const requestOptions = {
user_name: values.username,
password: values.password
}
try {
let res = await UseHttp({ url : USER.login, method:'POST', body: requestOptions});
setAuthHeader(res.token);
return res;
} catch (err) {
return err;
}
}
But when I call any other Api header for Authorization is not set there where CountryApi.js is
import UseHttp from './UseHttp';
import {LANDING} from './Url';
export const countryList = () => UseHttp({ url: LANDING.get_country_list });
and Country.js is this
import {countryList} from '../../../api/CountryApi';
useEffect(() => {
countryList().then((res) => {
setallData(res)
});
}, [locale])