我在应用程序开始时初始化了 axios 实例。在 Login.js 下,我能够获取令牌并希望使用拦截器将其添加到标头中,对于大多数后续 api 调用,例如在 AddSampleTable.js 下使用时。(其中一些也需要没有授权标头,例如 ForgotPassword.js)
目前我必须为每个组件中的每个 api 调用执行此操作。我当前的代码如下
axios.js
import axios from 'axios';
const baseURL = process.env.REACT_APP_BASE_URL;
let headers = {};
//this never executes since we havent logged in yet
//if(localStorage.token) {
//headers.Authorization = `Bearer ${localStorage.token}`;
//}
const token = localStorage.getItem('token');
const axiosInstance = axios.create({
baseURL: baseURL,
headers: {'Authorization': token? `Bearer ${token}`: null},
});
export default axiosInstance;
登录.js
import axiosInstance from '../../helpers/axios';
const printValues = e =>{
e.preventDefault();
axiosInstance.post('/auth', data)
.then(res =>{
console.log("writing token");
dispatch(jwtTokenRecieved(res.data.token));
localStorage.setItem('token',res.data.token);
const config = {
headers:{
Authorization:'Bearer '+res.data.token
}
}
axiosInstance.get('/User/GetUserByID/0', config)
.then(res =>{
dispatch(isLoggedUser(res.data));
})
.catch(err =>{
console.log(err);
})
AddSampleTable.js
这是我想使用实例的地方,默认情况下应该存在令牌,但目前我正在从 localstorage 中提取每个 api 调用
import axiosInstance from '../../helpers/axios';
export default function AddSamplesTable(){
const jwtToken = useSelector(state => state?.token?.data || '');
const retrieveSampleData = () =>{
const config = {
headers:{
Authorization:'Bearer '+ jwtToken,
'Content-Type': 'application/json'
}
}
axiosInstance.get('/batch/'+CoCData.id, config)
.then(function (response) {
setSamples(response.data.samples);
})
.catch(function (error) {
console.log(error);
});
}
}
注意我还使用reducers和actions将token设置到localStorage中,如你所见(除了通过setItem保存它)
dispatch(jwtTokenRecieved(res.data.token));
更新:我在创建函数后尝试在 axios.js 中使用拦截器,如下所示
axiosInstance.interceptors.request.use(
config => {
console.log(config)
const token = JSON.parse(localStorage.getItem('token'));
config.headers.Authorization = token ? `Bearer ${token}`: null;
return config;
}
);
但是当新用户登录时,现有令牌值不会用新令牌更新,我得到
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'status')