React(TypeScript)调用C# REST接口遇Fetch相关错误求助
解决React调用C# REST服务的连接重置与Fetch失败问题
以下是针对你遇到的net::ERR_CONNECTION_RESET和Uncaught (in promise) TypeError: Failed to fetch错误的排查与解决步骤:
1. 修正请求协议匹配后端服务
你的后端端口是44309(HTTPS常见变种端口),前端当前使用http://localhost:44309发起请求,可能和后端实际运行协议不匹配。将请求地址改为HTTPS:
const endpoint = 'https://localhost:44309/api/Users/Register';
2. 完善后端CORS配置
Postman不受浏览器CORS策略限制,但前端请求必须后端明确允许跨域。在C#项目中添加正确的CORS策略:
- .NET 6+(Program.cs):
builder.Services.AddCors(options => { options.AddPolicy("AllowFrontend", policy => policy.WithOrigins("http://localhost:3000") // 替换为你的前端实际地址 .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); // 如需携带Cookie则保留,否则可移除 }); // 放在app.UseRouting()之后、app.UseAuthorization()之前 app.UseCors("AllowFrontend");
- .NET Framework(Startup.cs):
public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowFrontend", builder => builder.WithOrigins("http://localhost:3000") .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 其他中间件之后添加 app.UseCors("AllowFrontend"); }
3. 校验前后端模型属性匹配
确保前端发送的字段与后端ApplicationUser类的属性完全匹配(包括大小写,除非配置了大小写不敏感绑定),若字段名不一致,可通过特性映射:
public class ApplicationUser { [JsonPropertyName("userName")] public string UserName { get; set; } [JsonPropertyName("confirmPassword")] public string ConfirmPassword { get; set; } // 其他属性... }
4. 排查后端未捕获异常
后端未处理的异常会直接导致连接重置,需添加异常捕获定位问题:
[HttpPost("[action]")] public IActionResult Register([FromBody] ApplicationUser applicationUser) { try { var userExists = _dbContext.AppUsers.FirstOrDefault(u => u.Email == applicationUser.Email); if (userExists != null) { return BadRequest("User with the same email address already exists"); } applicationUser.Password = HashService.HashPassword(applicationUser.Password); #if (!DEBUG) applicationUser.ConfirmPassword = "True"; #endif _dbContext.AppUsers.Add(applicationUser); _dbContext.SaveChanges(); return StatusCode(StatusCodes.Status201Created); } catch (Exception ex) { // 记录日志或直接返回错误信息,便于排查 return StatusCode(StatusCodes.Status500InternalServerError, $"Server error: {ex.Message}"); } }
重点检查HashService.HashPassword是否会因参数异常抛出错误,或数据库操作是否存在约束冲突。
5. 调整Fetch的Credentials配置
如果后端需要携带Cookie,将fetch的credentials改为include;若不需要,可尝试改为omit:
credentials: 'include', // 或 'omit'
6. 验证请求Body与Postman一致性
对比前端console.log(JSON.stringify(data))的输出和Postman中成功请求的JSON体,确保字段名称、数据类型完全一致,比如userTypeId是否为数字类型,密码是否符合后端格式要求。
内容的提问来源于stack exchange,提问作者Ron Owens
相关产品推荐
相关产品推荐

