【发布时间】:2017-02-23 00:53:52
【问题描述】:
我在我的 react/redux 应用程序中使用axios,当我遇到 401、404 等错误时,我目前在调用 axios 时必须为每个操作函数处理它们。我有一个 axios_config.js,其中我用一些常见的习语包装了 axios 调用。例如:
// need to move this to app config
const BASE_URL = 'http://localhost:8080/api/';
function config() {
return {
headers: {'X-Token-Auth': localStorage.getItem('token')}
}
}
export function fetchData(url) {
return axios.get(`${BASE_URL}${url}`, config());
};
我正在苦苦挣扎的是常见的错误,如 401、404 等。目前,我正在这样做:
export function fetchBrands() {
return function(dispatch) {
dispatch({type:FETCHING_BRANDS});
fetchData('brands')
.then(response => {
dispatch({
type: FETCH_BRANDS_SUCCESS,
payload: response
});
})
.catch(err => {
// deal with errors
});
}
}
但在 catch 块中,我不想每次都处理 401、404 等。因此,我需要能够在更全局的范围内处理这些问题,但仍然能够处理请求的特定错误,例如服务器端验证错误。
【问题讨论】:
标签: reactjs redux react-redux axios