当前位置:首页 > React

react如何统一处理401请求

2026-01-26 10:04:09React

统一处理401请求的方法

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

使用axios拦截器

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

react如何统一处理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

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

react如何统一处理401请求

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
分享给朋友:

相关文章

react 如何引入jquery

react 如何引入jquery

引入 jQuery 到 React 项目 在 React 项目中引入 jQuery 可以通过多种方式实现,但需要注意 React 和 jQuery 操作 DOM 的方式可能冲突,因此建议仅在必要时使用…

如何下载react

如何下载react

下载 React 的方法 通过 npm 或 yarn 安装 React 可以通过包管理器 npm 或 yarn 安装。确保已安装 Node.js(包含 npm),然后在项目目录中运行以下命令:…

react 如何调试

react 如何调试

调试 React 应用的方法 使用 React Developer Tools 安装 Chrome 或 Firefox 的 React Developer Tools 扩展,可以检查组件树、状态和 p…

如何关闭react

如何关闭react

关闭React应用的步骤 在开发或运行React应用时,可能需要关闭正在运行的开发服务器或停止应用。以下是几种常见情况的处理方法: 停止开发服务器 如果正在使用npm start或yarn star…

react如何启动

react如何启动

启动 React 项目的步骤 确保已安装 Node.js React 需要 Node.js 环境运行,建议安装最新稳定版(LTS)。可通过以下命令检查是否已安装: node -v npm -v…

react如何引入echarts

react如何引入echarts

安装 ECharts 依赖 在 React 项目中安装 ECharts 核心库和 React 封装库: npm install echarts echarts-for-react 基础引入方式 创建…