【发布时间】:2017-08-20 10:46:32
【问题描述】:
我有一个从 api 服务器获取令牌的 react/redux 应用程序。在用户进行身份验证后,我想让所有 axios 请求都将该令牌作为 Authorization 标头,而不必手动将其附加到操作中的每个请求。我对 react/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;
}
}
我的令牌存储在 state.session.token 下的 redux 存储中。
我有点不知道如何继续。我尝试在我的根目录中的文件中创建 axios instance 并更新/导入它而不是从 node_modules 但是当状态更改时它没有附加标题。非常感谢任何反馈/想法,谢谢。
【问题讨论】:
-
从服务器接收到授权令牌后,您将授权令牌存储在哪里?本地存储?
-
在 redux 存储 session.token 中