Reputation: 4848
first i use localStorage.setItem
to save a token that i've taken from api and set it as header in my axios
i need to use local.storage.getItem()
to read the data and then set it as header
so there is another action which sends request ,takes the token and saves it to local storage by localStorage.setItem()
and replaces the browser history to where i'm calling the action that needs the token ,but it shows 404 error with the only first error which means only at the first time and if i close the page and open it again it works fine
I'll show the code step by step
here is my code where i want to use the token
import axios from 'axios';
const token = localStorage.getItem('token')//here doesn't get it and shows 404 error from API i refresh the page for second time or after
export default axios.create({
headers:{"Authorization": `Bearer ${token}`}
})
here is my action where i get the token with diffrent instance of axios which has no header
export const sendCode = (phone, code) => async dispatch => {
dispatch({ type: LOADING_STATE })
const response =
await loginApi.post(baseurl + "Auth/Checkcode", {
phone: phone,
code: code
},
)
dispatch({ type: SEND_CODE, payload: response.data });
if (response.data.success === true) {
history.replace('/home')
localStorage.setItem("token", response.data.obj.token)
}
and finally here is the action that i call it with the instance that has header
export const getHomeInfo = () => async dispatch => {
dispatch({type:LOADING_STATE})
const response = await homeAPI.get(baseurl + "Home/GetList")//homeAPI is the instance that has header
dispatch({ type: GET_HOME_INFO, payload: response.data })
};
Upvotes: 0
Views: 1309
Reputation: 64
import axios from 'axios';
const token = localStorage.getItem('token')
export default axios.create({
headers:{"Authorization": `Bearer ${token}`}
})
Here, token will be fetch once when the js file is bundled, you have to refetch it each time :
import axios from 'axios';
const getHeaders = () => {
const token = localStorage.getItem('token')
return {"Authorization": `Bearer ${token}`}
}
export default axios.create({
headers: getHeaders()
})
EDIT : The code above does not work since axios.create() is called only once, if you need dynamic headers, you should add an interceptor which will be called before each request :
const axiosInstance = axios.create()
axiosInstance.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error),
);
export default axiosInstance
Upvotes: 3