我有一个react / redux应用程序,可从api服务器获取令牌。用户验证后,我想使所有axios请求都将该令牌作为Authorization标头,而不必手动将其附加到操作中的每个请求。我是新来的人,对React / Redux做出反应,不确定最好的方法,也没有在Google上找到任何高质量的点击。
这是我的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存储中state.session.token
。
我对如何进行有点迷茫。我试过在根目录中的文件中创建一个axios实例,并更新/导入该实例,而不是从node_modules导入/更新,但状态更改时它没有附加标头。非常感谢任何反馈/想法。