You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJs中Axios响应状态码恒为0,但网络显示401的问题解决

解决方案:Axios拦截器无法获取401状态码,返回status=0的问题

核心原因

出现error.response.status=0但浏览器网络面板显示401,本质是浏览器因跨域规则拦截了响应,没有将真实的401响应传递给Axios。即使后端加了@CrossOrigin,也可能存在配置不全的情况,比如预检请求(OPTIONS)失败、未允许自定义请求头或凭证等。

分步解决

1. 完善后端Spring Boot的CORS配置

单独的@CrossOrigin注解可能覆盖不全,建议用全局CORS配置,同时兼容Spring Security(如果有):

全局CORS配置类

@Configuration
public class GlobalCorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                // 替换为你的前端实际域名,生产环境不要用*
                .allowedOrigins("http://localhost:3000")
                // 允许所有HTTP方法,包括预检的OPTIONS
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                // 允许自定义请求头(比如Authorization)
                .allowedHeaders("*")
                // 如果请求带cookie或token,必须开启这个
                .allowCredentials(true)
                // 预检请求缓存时长,减少OPTIONS请求次数
                .maxAge(3600);
    }
}

若使用Spring Security,需额外配置允许OPTIONS请求

Spring Security默认会拦截OPTIONS请求,导致预检失败,需要在Security配置中放行:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 启用CORS配置
                .cors().and()
                .authorizeRequests()
                // 放行所有OPTIONS请求
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                // 其他权限配置...
                .anyRequest().authenticated();
    }
}

2. 检查Axios请求配置

确保请求携带凭证(如果需要),并正确设置请求头:

// 创建Axios实例时配置
const axiosInstance = axios.create({
    baseURL: 'http://your-backend-domain:port',
    // 如果请求需要带cookie或token,必须开启这个
    withCredentials: true,
    headers: {
        'Content-Type': 'application/json'
    }
});

3. 调整Axios响应拦截器的错误处理

区分真实响应错误和跨域/网络错误,避免误判:

axiosInstance.interceptors.response.use(
    response => response,
    error => {
        // 无response的情况:跨域拦截、网络断开等
        if (!error.response) {
            console.error('跨域或网络异常,请检查后端CORS配置:', error.message);
            return Promise.reject(error);
        }

        // 拿到真实状态码后处理
        const { status } = error.response;
        if (status === 401) {
            // 触发你的自定义逻辑,比如跳登录页、清除token
            handleUnauthorized();
        }

        return Promise.reject(error);
    }
);

4. 不需要更换请求库

fetch、axios等前端请求库都会受浏览器跨域规则限制,换库无法解决本质问题,先排查并修复CORS配置即可。

内容的提问来源于stack exchange,提问作者samet yılmaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:50:29