首页 > 解决方案 > 如果我使用 axios 收到 404 错误,如何重定向?

问题描述

如果我收到 404 错误,除了一个路由 - /api/profile 之外,我想重定向。

我使用 axios,我不确定是否可以在这种情况下使用拦截器。

我可以做这样的事情吗?

axios.interceptors.response.use( ( response ) => {
    return response;
}, ( error ) => {
    if ( error.response.status === 404 && error.config.url !== '/api/profile' ) {
        history.push( '/not-found' ); 
        return Promise.reject( error );
    }   
    return Promise.reject( error );
});

还是我应该坚持这一点:

axios.get( '/api/something' ).then( ( res ) => {
    dispatch({
        type: GET_SOMETHING,
        payload: res.data
    });
}).catch( ( err ) => {
    if ( err.response.status == 404 ) {
        history.push( '/not-found' );
    }
});

谢谢

标签: reactjsexpressmongooseaxiosredux-thunk

解决方案


推荐阅读