Fetch API 不会自动处理 401 状态码重定向,401 是服务端返回的合法响应,需前端手动判断并跳转登录页或刷新凭证;应检查 response.status === 401,在 then 中处理而非 catch;推荐封装 authFetch 统一拦截 401 并清除 token、跳转登录;跨域时需显式设置 credentials: 'include' 以发送认证凭证。

Fetch API 本身不会自动处理 401 状态码的重定向——它根本不会重定向,401 就是响应,需要你手动判断并跳转登录页或刷新凭证。
理解 401 和重定向的关系
401(Unauthorized)表示请求缺少有效认证凭证,不是“需要跳转”,而是“当前请求被拒绝”。所谓“401 重定向”,其实是前端在收到 401 后,主动跳转到登录页(如 /login),而不是服务端返回 302。服务端对未认证请求返回 401 是标准做法,不应自动重定向(否则会掩盖认证失败原因,且不利于 API 调用方控制流程)。
在 fetch 中捕获并响应 401
你需要检查 response.status,并在为 401 时执行跳转或重新认证逻辑:
- 用 response.ok 或显式判断 response.status === 401
- 避免在 catch 中处理 401——网络错误才进 catch,401 是合法 HTTP 响应,会进 then
- 跳转前可清除本地 token,防止下次请求继续携带无效凭证
示例:
fetch('/api/profile', {
headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
})
.then(res => {
if (res.status === 401) {
localStorage.removeItem('token');
window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname);
return;
}
if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
return res.json();
})
.then(data => console.log(data))
.catch(err => console.error('Fetch failed:', err));
统一处理所有请求的 401(推荐封装)
把认证逻辑抽离成自定义 fetch 函数,便于复用和维护:
- 拦截每个响应,统一判断 401
- 支持 Promise 链式调用,不破坏原有使用习惯
- 可集成 token 自动刷新(如用 refresh token 换新 access token 后重发原请求)
简易封装示例:
async function authFetch(input, init = {}) {
const token = localStorage.getItem('token');
if (token) {
init.headers = {
...init.headers,
'Authorization': `Bearer ${token}`
};
}
const res = await fetch(input, init);
if (res.status === 401) {
localStorage.removeItem('token');
window.location.replace('/login?redirect=' + encodeURIComponent(window.location.pathname));
throw new Error('Unauthorized: redirected to login');
}
return res;
}
// 使用方式不变
authFetch('/api/dashboard')
.then(r => r.json())
.then(console.log);
注意跨域与 credentials
如果 API 在不同域名下,且依赖 Cookie 认证,需显式设置 credentials: 'include',否则浏览器不会发送 Cookie,服务端可能直接返回 401:
- 不加 credentials:默认 omit,不带 Cookie 或 Authorization 头
- credentials: 'include':始终发送凭证(需后端允许 CORS 的 credentials)
- credentials: 'same-origin':同源时发送(默认行为,但显式写出更清晰)
例如:fetch('/api/data', { credentials: 'include' })
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











