【发布时间】:2019-12-29 10:12:20
【问题描述】:
我正在为 API 调用创建带有 redux(+thunk+persistant)和 axios(+ 用于刷新令牌的拦截器)的 RN 应用程序。
我将我的应用程序逻辑组织为单独的文件,其中包含与 axios API 调用(因为这对我来说非常清楚)和不同文件中的 reducer 相结合的操作。
问题在于刷新令牌应该在动作文件中处理。
例如简单的动作文件“projects.js”:
import createAuthRefreshInterceptor from 'axios-auth-refresh';
import axios from 'axios';
const refreshAuthLogic = failedRequest => axios.post('http://domain.pl/api/refresh-token').then(tokenRefreshResponse => {
// >>>> save token to persistant part of REDUX ?????
failedRequest.response.config.headers['Authorization'] = 'Bearer ' + // >>>> get token from persistant part of REDUX ?????;
return Promise.resolve();
});
/*
* action types
*/
export const FETCH_PROJECTS = 'FETCH_PROJECTS'
/*
* API URL & config
*/
const apiUrl = 'http://domain.pl/api/projects';
/*
* action creators
*/
export const fetchProjects = () => {
return (dispatch, getState) => {
const state = getState();
createAuthRefreshInterceptor(axios, refreshAuthLogic);
return axios.get(apiUrl, {headers: {'Authorization': "bearer " + state.auth.user.access_token }})
.then(response => {
dispatch(fetchProjectsSuccess(response.data))
})
.catch(error => {
throw(error);
});
};
};
export const fetchProjectsSuccess = (projects) => {
return {
type: FETCH_PROJECTS,
projects: projects
}
};
我正在尝试像下面那样执行此操作,但总是会出现一些错误。 Accessing Redux state in an action creator?
在操作文件 (axios+redux) 中处理访问/刷新令牌的最佳方法是什么?
谢谢!
【问题讨论】:
标签: react-native redux axios interceptor persistent-storage