react如何统一处理401请求
统一处理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的项目。根据项目规模和架构选择最合适的方案。






