React/TypeScript前端用Axios向C#后端POST请求报错net::ERR_EMPTY_RESPONSE
问题:React+TypeScript通过Axios调用C#后端POST请求出现ERR_EMPTY_RESPONSE错误
控制台抛出错误:
AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}xhr.js:220 POST http://localhost:7104/api/Authorisation/LogIn net::ERR_EMPTY_RESPONSE
相关代码
React组件代码
import { Component } from "react" import axios from 'axios' export class MainPage extends Component<any, any>{ constructor(props: string){ super(props) this.state = { login: '', password: '' } } handleUsernameChange = (event: any) => { this.setState({ login: event.target.value }) } handlePasswordChange = (event:any) => { this.setState({ password: event.target.value }) } submitHandler = (event: any) => { event.preventDefault() console.log(this.state) axios.post('http://localhost:7104/api/Authorisation/LogIn', this.state) .then(response =>{ console.log(response) }) .catch(error => { console.log(error) }) } showLogin = () => { ... } render (){ return ( ... <form className="login-section" onSubmit={this.submitHandler}> <button type="submit" className="left-button" id="left-button" onMouseOver={() => this.showLogin()} ><img className="log-in-icon" src="ICONS/log-in.png"/>Log In</button> <input id="userName-input" name="username" value={this.state.username} onChange={this.handleUsernameChange}/> <input id="password-input" name="password" value={this.state.password} onChange={this.handlePasswordChange} type="password"/> </form> ... )} }
后端Program.cs代码
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; using Microsoft.IdentityModel.Tokens; using RecipeDate.Application; using RecipeDate.Infrastructure; using RecipeDate.Infrastructure.Persistance; using RecipeDate.Infrastructure.UserModels; var builder = WebApplication.CreateBuilder(args); var MyAllowSpecificOrigins = "_myAllowSpecificOrigins"; // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddInfrastructure(builder.Configuration); builder.Services.AddApplication(); builder.Services.AddIdentity<UserRecipeDate, IdentityRole>() .AddEntityFrameworkStores<AppDbContext>(); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer( options => options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidIssuer = builder.Configuration.GetSection("Jwt:Issuer").Value, ValidAudience = builder.Configuration.GetSection("Jwt:Audiene").Value }); builder.Services.AddCors(options => { options.AddPolicy(name: MyAllowSpecificOrigins, policy => { policy.WithOrigins("http://localhost:3000", "https://localhost:3000"); policy.AllowAnyHeader(); policy.AllowAnyMethod(); }); }); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseCors(MyAllowSpecificOrigins); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();
后端AuthorisationController代码
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; using RecipeDate.Application.Services.Interfaces; using RecipeDate.Infrastructure.UserModels; namespace RecipeDate.API.Controllers { [ApiController] [Route("api/[controller]")] public class AuthorisationController : Controller { private readonly IAuthorisationServices _authorisationServices; public AuthorisationController(IAuthorisationServices authorisationServices) { _authorisationServices = authorisationServices; } [EnableCors] [HttpPost] [Route("LogIn")] [AllowAnonymous] public async Task LogInAsync([FromBody]string login, string password) { await _authorisationServices.LogInUserAsync(login, password); } [HttpPost] [Route("Register")] [AllowAnonymous] public async Task RegisterAsync(UserDto user) { await _authorisationServices.RegisterUserAsync(user); } } }
解决步骤
- 修复后端接口参数绑定问题
JSON请求体只能绑定到一个对象,不能同时用两个[FromBody]参数。先创建登录请求DTO类:
public class LoginRequest { public string Login { get; set; } public string Password { get; set; } }
再修改控制器Action:
[EnableCors] [HttpPost("LogIn")] [AllowAnonymous] public async Task<IActionResult> LogInAsync([FromBody] LoginRequest request) { var loginResult = await _authorisationServices.LogInUserAsync(request.Login, request.Password); // 根据实际登录逻辑返回对应响应 if (loginResult.IsSuccess) return Ok(new { Token = loginResult.Token }); else return BadRequest(new { Message = "登录失败,账号或密码错误" }); }
确保后端返回有效响应
原Action返回async Task(无返回值)会导致浏览器收到空响应,必须返回IActionResult或派生类型,给前端明确的HTTP状态码和响应内容。修复前端输入框状态绑定错误
前端用户名输入框的value绑定了this.state.username,但state中对应的字段是login,修改为:
<input id="userName-input" name="username" value={this.state.login} onChange={this.handleUsernameChange}/>
- 验证CORS配置(可选)
如果上述修改后仍有问题,可临时放宽CORS策略用于调试:
policy.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod();
上线前再改回指定的前端域名。
内容的提问来源于stack exchange,提问作者Kond Videos
相关产品推荐
相关产品推荐

