处理 axios react-redux 应用程序中的 401 未授权错误

Posted

技术标签:

【中文标题】处理 axios react-redux 应用程序中的 401 未授权错误【英文标题】:Handling 401 unauthorised error in axios react-redux application 【发布时间】:2019-06-04 04:41:16 【问题描述】:

我想在我的服务器输出 401 未经授权的错误时处理它,我想调度一个动作来做到这一点。我看到很多人都在使用 axios.interceptors 我该怎么做。什么是拦截器?请详细解释它是什么并帮助我。我是 react-redux 框架的新手。这是我在 express 中的路由处理程序:

router.get('/api/me', function(req, res) 

        if(req.user) 
            res.status(200).send(
                email : req.user.local.email,
                isCurrentUser: true
            );
        else 
            res.status(401).send(
                isCurrentUser: false
            )
        



)

这是我的异步操作创建者:

export const fetchCurrentUser =  () => 

    return async (dispatch) => 

        const res =  await axios.get(`$ROOT_URL/me`); 
        if(res.status === 200) 
              dispatch( type: types.YES_FETCH_CURRENT_USER, payload: res.data );
        else if(res.status === 401) 
             dispatch(type: types.NO_FETCH_CURRENT_USER)
        


    

;

【问题讨论】:

【参考方案1】:

拦截器位于axios 中。您可以将拦截器与 express 中的中间件进行比较。你使用拦截器来

在请求被执行之前拦截它。 在您将响应作为 Promise 处理之前拦截它。

有关其用法的文档可以在here找到。

在您的情况下,您可以执行以下操作:

const aiosInstance = axios.create();

axiosInstance.interceptors.response.use(
  (response) => response,
  (error) => 
    if (error.response.status === 401) 
      // dispatch something to your store
    

    return Promise.reject(error);
  
)

axiosInstance.get(`$ROOT_URL/me`); 

上面的例子确实意味着你必须导入你的 redux 存储实例来直接调度一个动作。

编辑我的回答基于以下对话:

试试:

export const fetchCurrentUser =  () => async (dispatch) => 
  try 
    const res = await axios.get(`$ROOT_URL/me`); 

    dispatch( type: types.YES_FETCH_CURRENT_USER, payload: res.data );
   catch (err) 
    dispatch(type: types.NO_FETCH_CURRENT_USER)
  
;

【讨论】:

我不想使用拦截器,你能在直接 axios 请求的地方显示代码吗 我试过这个:export const fetchCurrentUser = () => return async (dispatch) => try const res = await axios.get($ROOT_URL/me); if(res.status === 200) dispatch( type: types.YES_FETCH_CURRENT_USER, payload: res.data ); catch(error) if(error.response.status === 401) dispatch(type: types.NO_FETCH_CURRENT_USER) ; 我仍然在控制台中收到以下错误:GET localhost:5000/api/me 401 (Unauthorized) 您的问题说明了拦截器是什么。似乎您遇到的问题与您所描述的问题不同。您的前端目前非常好。在您的后端,您正在检查 req.user - 但默认情况下,req 参数上未设置“用户”属性。因此,您的 if 条件返回 false,这会导致您收到 401 响应。 您是否在 express 中使用中间件来设置 req.user 变量?

以上是关于处理 axios react-redux 应用程序中的 401 未授权错误的主要内容,如果未能解决你的问题,请参考以下文章

每个 axios 请求在 react-redux 应用程序中触发两次?

如何使用 react-redux 存储令牌并在多个 axios 请求中使用它?

在 react-redux 应用程序中使用默认错误处理管理 API 调用

如何在客户端处理 CORS 错误(React-Redux-Axios)

使用react+redux+react-redux+react-router+axios+scss技术栈从0到1开发一个applist应用

反应本机中未处理的承诺拒绝错误?