我有一个react/redux应用程序,它从api服务器获取 token 。用户进行身份验证后,我想让所有 axios 请求都将该 token 作为授权 header ,而不必手动将其附加到操作中的每个请求。我对 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;
}
}
我的 token 存储在 state.session.token
下的 redux 存储中。
我有点不知道如何继续。我尝试过制作 axios instance在我的根目录中的一个文件中,并更新/导入它,而不是从node_modules,但当状态更改时它不会附加 header 。非常感谢任何反馈/想法,谢谢。
最佳答案
有多种方法可以实现这一目标。在这里,我解释了两种最常见的方法。
1.您可以使用axios interceptors拦截任何请求并添加授权 header 。
// Add a request interceptor
axios.interceptors.request.use(function (config) {
const token = store.getState().session.token;
config.headers.Authorization = token;
return config;
});
2.来自 documentation在 axios
中,您可以看到有一种可用机制,允许您设置默认 header ,该 header 将随您发出的每个请求一起发送。
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
所以在你的情况下:
axios.defaults.headers.common['Authorization'] = store.getState().session.token;
如果需要,您可以创建一个自执行函数,当 token 存在于商店中时,该函数将自行设置授权 header 。
(function() {
String token = store.getState().session.token;
if (token) {
axios.defaults.headers.common['Authorization'] = token;
} else {
axios.defaults.headers.common['Authorization'] = null;
/*if setting null does not remove `Authorization` header then try
delete axios.defaults.headers.common['Authorization'];
*/
}
})();
现在您不再需要手动将 token 附加到每个请求。您可以将上述函数放在保证每次都会执行的文件中(例如:包含路由的文件)。
关于reactjs - 为所有 axios 请求附加授权 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43051291/