我有一个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。
state.session.token
我对如何进行有点迷茫。我试过在根目录中的文件中创建一个axios实例,并更新/导入该实例(而不是从node_modules导入),但是当状态更改时,它不会附加标头。非常感谢任何反馈/想法。
有多种方法可以实现此目的。在这里,我解释了两种最常见的方法。
1.您可以使用axios拦截器来拦截任何请求并添加授权标头。
// Add a request interceptor axios.interceptors.request.use(function (config) { const token = store.getState().session.token; config.headers.Authorization = token; return config; });
2.从您的文档中axios可以看到有一种可用的机制,该机制可让您设置默认标头,该标头将随您提出的每个请求一起发送。
axios
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
因此,在您的情况下:
axios.defaults.headers.common['Authorization'] = store.getState().session.token;
如果需要,您可以创建一个自执行函数,当令牌存在于商店中时将自行设置授权标头。
(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']; */ } })();
现在,您不再需要将令牌手动附加到每个请求。您可以将上述功能放在保证每次都执行的文件中( 例如: 包含路径的文件)。
希望能帮助到你 :)