当前位置:首页 > React

react如何统一处理401请求

2026-01-26 10:04:09React

统一处理401请求的方法

在React应用中,401状态码通常表示未授权或会话过期。以下是几种常见的统一处理方式:

使用axios拦截器

配置axios的请求和响应拦截器,全局捕获401错误并跳转登录页:

import axios from 'axios';
import { history } from './history'; // 自定义history对象

axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response.status === 401) {
      localStorage.removeItem('token');
      history.push('/login');
    }
    return Promise.reject(error);
  }
);

封装自定义fetch

创建封装后的请求函数,处理所有请求的401状态:

async function customFetch(url, options) {
  const response = await fetch(url, {
    ...options,
    headers: {
      'Authorization': `Bearer ${localStorage.getItem('token')}`,
      ...options.headers
    }
  });

  if (response.status === 401) {
    window.location.href = '/login';
    throw new Error('Unauthorized');
  }

  return response;
}

使用React Context

创建全局的请求上下文,统一管理认证状态:

const AuthContext = createContext();

function AuthProvider({ children }) {
  const [isAuth, setIsAuth] = useState(false);

  const checkAuth = async () => {
    try {
      const res = await axios.get('/api/check-auth');
      setIsAuth(true);
    } catch (err) {
      if (err.response.status === 401) {
        setIsAuth(false);
        window.location.href = '/login';
      }
    }
  };

  useEffect(() => {
    checkAuth();
  }, []);

  return (
    <AuthContext.Provider value={{ isAuth, checkAuth }}>
      {children}
    </AuthContext.Provider>
  );
}

高阶组件方式

创建HOC包装需要认证的组件:

function withAuth(Component) {
  return function AuthenticatedComponent(props) {
    const [auth, setAuth] = useState(true);

    useEffect(() => {
      axios.get('/api/check-auth')
        .catch(err => {
          if (err.response.status === 401) {
            setAuth(false);
            window.location.href = '/login';
          }
        });
    }, []);

    return auth ? <Component {...props} /> : null;
  };
}

Redux中间件方案

对于使用Redux的应用,可以创建处理401的中间件:

const authMiddleware = store => next => action => {
  if (action.payload && action.payload.status === 401) {
    store.dispatch({ type: 'LOGOUT' });
    window.location.href = '/login';
  }
  return next(action);
};

每种方法各有优缺点,axios拦截器适合大多数场景,Context方案更适合需要全局状态管理的应用,而Redux中间件则适合已使用Redux的项目。根据项目规模和架构选择最合适的方案。

react如何统一处理401请求

标签: react
分享给朋友:

相关文章

电脑如何安装react

电脑如何安装react

安装 Node.js 和 npm React 项目依赖 Node.js 环境,需先安装 Node.js(自带 npm)。访问 Node.js 官网 下载 LTS 版本,运行安装程序并完成配置。安装后,…

react中monent如何获取日期

react中monent如何获取日期

使用 Moment.js 获取当前日期 在 React 中通过 Moment.js 获取当前日期,可以直接调用 moment() 函数。它会返回包含当前日期和时间的 Moment 对象。 impor…

电脑如何安装react

电脑如何安装react

安装 Node.js 和 npm React 依赖于 Node.js 和 npm(Node Package Manager)。从 Node.js 官网下载并安装最新稳定版本,安装完成后会自动包含 np…

react moment如何使用

react moment如何使用

安装 react-moment 通过 npm 或 yarn 安装 react-moment: npm install react-moment 或 yarn add react-moment…

如何降低react版本

如何降低react版本

降低 React 项目版本的步骤 检查当前 React 版本 运行以下命令查看项目中安装的 React 当前版本: npm list react 或 yarn list react 修改…

react如何开发组件

react如何开发组件

React 组件开发基础 React 组件分为函数组件和类组件两种形式。函数组件是现代 React 开发的主流方式,结合 Hooks 可以实现完整功能。 函数组件示例: function Gree…