1 回答

TA貢獻1770條經驗 獲得超3個贊
在您的示例中,您在加載文件時為 axios 設置令牌。這意味著只有在應用程序加載時,而不是在您登錄后。所以那個localStorage時候那個項目是空的。
所以解決方案是為 axios 設置攔截器而不是你的實例authAxios:
const App = (props) => {
// This will trigger when only once when page refreshes
useEffect(() => {
axios.interceptors.request.use(
(config) => {
config.headers = {
...config.headers,
Authorization: `Token ${token ? localStorage.getItem("token") : null}`
};
return config;
},
(error) => {
props.dispatchRedirectToLoginPage()
return Promise.reject(error);
}
);
}, [])
return <div>Your app</div>
}
這樣每個請求都會執行這個函數,它會從 localStorage 中獲取令牌。
您進行的每個 api 調用都可以使用axios.get(...)或使用您需要的任何方法。
添加回答
舉報