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 })
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…