React中Fetch请求报TypeError: Failed to fetch但API正常返回数据求助
解决React Fetch请求ASP.NET Core API时的"TypeError: Failed to fetch"问题
看起来你的API本身能正常返回数据,但客户端Fetch请求失败,结合你的代码细节,大概率是CORS配置问题或者认证凭证传递问题——毕竟你的API加了[Authorize]属性,且Fetch请求带了credentials: 'include',这两个点很容易踩坑,我给你一步步排查方案:
1. 先排查CORS配置(最常见原因)
当Fetch请求带credentials: 'include'时,ASP.NET Core的CORS策略必须满足两个核心要求:
- 不能使用通配符
*作为允许的Origin,必须指定你的React应用的具体运行地址(比如http://localhost:3000) - 必须显式启用
AllowCredentials()来允许携带凭证
在你的ASP.NET Core项目的Startup.cs里修改配置:
在ConfigureServices方法中添加CORS策略:
services.AddCors(options => { options.AddPolicy("AllowReactClient", builder => { // 替换成你的React应用实际运行地址 builder.WithOrigins("http://localhost:3000") .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); // 关键:允许请求携带凭证 }); });
在Configure方法中启用CORS(注意中间件顺序):
要确保UseCors放在UseAuthentication和UseMvc之前,否则CORS验证会失效:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseCors("AllowReactClient"); // 先启用CORS策略 app.UseAuthentication(); // 再处理认证逻辑 app.UseMvc(); }
2. 检查认证凭证的传递
因为你的API加了[Authorize],请求必须携带有效的认证信息才能通过校验:
如果是Cookie认证:
- 要确保Cookie支持跨域传递,在
Startup.cs的ConfigureServices里配置Cookie属性:services.ConfigureApplicationCookie(options => { options.Cookie.SameSite = SameSiteMode.None; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // 适配HTTPS环境 options.Cookie.HttpOnly = true; }); - 同时要确保用户已通过浏览器登录(比如调用过API的登录接口),否则未认证的请求会被拒绝,也会触发Fetch错误。
- 要确保Cookie支持跨域传递,在
如果是JWT认证:
- 需要在Fetch请求的headers里手动添加Authorization头,携带JWT令牌:
const token = "你的JWT令牌内容"; const response = await fetch('https://localhost:44365/api/values/', { method: 'GET', credentials: 'include', mode: 'cors', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` } });
- 需要在Fetch请求的headers里手动添加Authorization头,携带JWT令牌:
3. 优化Fetch请求的错误处理
你当前的代码混合了async/await和.then(),且catch里只输出模糊的"error",很难定位具体问题。建议改成统一的try/catch写法,方便查看详细错误信息:
testButton = async () => { try { const response = await fetch('https://localhost:44365/api/values/', { method: 'GET', credentials: 'include', mode: 'cors', headers: { 'Content-Type': 'application/json' } }); // 主动检查响应状态码,非2xx的请求也要抛出错误 if (!response.ok) { throw new Error(`请求失败:状态码${response.status},信息${response.statusText}`); } const json = await response.json(); console.log('获取到的数据:', json); return json; } catch (e) { console.error('Fetch请求错误详情:', e); } }
4. 快速验证排查
可以先临时移除API控制器上的[Authorize]属性,再测试Fetch请求:
- 如果能成功拿到数据,说明问题出在认证凭证传递或者CORS允许凭证的配置上
- 如果还是失败,那大概率是CORS配置有误,再回头检查Origin是否正确、中间件顺序是否符合要求
按照这些步骤排查,应该能解决你的问题。
内容的提问来源于stack exchange,提问作者anhtv13
相关产品推荐
相关产品推荐

