我有一个使用React/Redux编写的应用程序,从API服务器获取token。用户验证后,我想在所有axios请求中自动添加该token作为Authorization标头,而不必在每个操作中手动附加它。我对React/Redux比较新,不确定最佳方法,并且在Google上没有找到什么质量高的信息。
以下是我的Redux设置:
以下是我的Redux设置:
// actions.js
import axios from 'axios';
export function loginUser(props) {
const url = `https://api.mydomain.com/login/`;
const { email, password } = props;
const request = axios.post(url, { email, password });
return {
type: LOGIN_USER,
payload: request
};
}
export function fetchPages() {
/* here is where I'd like the header to be attached automatically if the user
has logged in */
const request = axios.get(PAGES_URL);
return {
type: FETCH_PAGES,
payload: request
};
}
// reducers.js
const initialState = {
isAuthenticated: false,
token: null
};
export default (state = initialState, action) => {
switch(action.type) {
case LOGIN_USER:
// here is where I believe I should be attaching the header to all axios requests.
return {
token: action.payload.data.key,
isAuthenticated: true
};
case LOGOUT_USER:
// i would remove the header from all axios requests here.
return initialState;
default:
return state;
}
}
我的令牌存储在redux store下的state.session.token
中。
我有点迷失在如何继续下去。我尝试在根目录的文件中创建一个axios实例,并更新/导入它而不是从node_modules中导入,但是当状态改变时它没有附加头文件。非常感谢任何反馈/想法。