React注册表单无法提交至ASP.NET Core 3.1后端更新SQL Server数据库
电商网站注册功能报错排查
问题概述
我是Stack Overflow新手,编程经验较浅,正在为毕业设计开发电商网站。已完成SQL Server数据库创建、API控制器和React前端开发,React注册表单能获取输入数据,但提交时报错:
- 有时出现网络错误:
AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
xhr.js:251 POST http://localhost:56400/api/Registration/Registration net::ERR_NETWORK_CHANGED
- 有时出现404错误(根据网页打开位置不同)
开发环境:用VS Code写前端,关联VS 2019运行,默认显示React页面而非Weather页面,均使用Chrome。VS 2019运行时的错误日志:
POST http://localhost:56400/api/Registration/Registration 404 (Not Found) dispatchXhrRequest @ xhr.js:251 xhr @ xhr.js:49 dispatchRequest @ dispatchRequest.js:51 request @ Axios.js:148 httpMethod @ Axios.js:187 wrap @ bind.js:5 handleSave @ Registration.js:40 onClick @ Registration.js:131 callCallback @ react-dom.development.js:4164 invokeGuardedCallbackDev @ react-dom.development.js:4213 invokeGuardedCallback @ react-dom.development.js:4277 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291 executeDispatch @ react-dom.development.js:9041 processDispatchQueueItemsInOrder @ react-dom.development.js:9073 processDispatchQueue @ react-dom.development.js:9086 dispatchEventsForPlugins @ react-dom.development.js:9097 (anonymous) @ react-dom.development.js:9288 batchedUpdates$1 @ react-dom.development.js:26140 batchedUpdates @ react-dom.development.js:3991 dispatchEventForPluginEventSystem @ react-dom.development.js:9287 dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465 dispatchEvent @ react-dom.development.js:6457 dispatchDiscreteEvent @ react-dom.development.js:6430 Registration.js:45 AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
已做排查:取消SSL改用HTTP,启用CORS,React的.env文件添加WDS_SOCKET_PORT=0,确认VS与SQL Server连接正常。
代码参考
后端Registration控制器
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace *********_.Controllers { [Route("api/[controller]")] [ApiController] public class RegistrationController : ControllerBase { private readonly IConfiguration _configuration; public RegistrationController(IConfiguration configuration) { _configuration = configuration; } [HttpPost] [Route("Registration")] public Response Registration(Registration registration) { Response response = new Response(); SqlConnection connection = new SqlConnection(_configuration.GetConnectionString("ConnectionString").ToString()); DAL dal = new DAL(); response = dal.Registration(registration, connection); return response; } [HttpPost] [Route("Login")] public Response Login(Registration registration) { Response response = new Response(); SqlConnection connection = new SqlConnection(_configuration.GetConnectionString("ConnectionString").ToString()); DAL dal = new DAL(); response = dal.Login(registration, connection); return response; } [HttpPost] [Route("UserApproval")] public Response UserApproval(Registration registration) { Response response = new Response(); SqlConnection connection = new SqlConnection(_configuration.GetConnectionString("ConnectionString").ToString()); DAL dal = new DAL(); response = dal.UserApproval(registration, connection); return response; } } }
后端Registration模型
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace **********_.Models { public class Registration { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string StreetAddress { get; set; } public string Apartment { get; set; } public string City { get; set; } public int ZipCode { get; set; } public string Country { get; set; } public string Password { get; set; } public string Email { get; set; } public int Phone { get; set; } public int IsActive { get; set; } public int IsApproved { get; set; } } }
前端Registration组件
import React, { useState } from 'react'; import axios from 'axios'; import UserNavBar from './UserNavBar'; import EWholism_Image2 from './EWholism_Image2.jpg'; function Registration() { const [FirstName, setFirstName] = useState('') const [LastName, setLastName] = useState('') const [StreetAddress, SetStreetAddress] = useState('') const [Apartment, setApartment] = useState('') const [City, setCity] = useState('') const [ZipCode, setZipCode] = useState('') const [Country, setCountry] = useState('') const [Email, setEmail] = useState('') const [Password, setPassword] = useState('') const [Phone, setPhone] = useState('') const handleSave =(e) => { e.preventDefault(); console.log(FirstName, LastName, StreetAddress, Apartment, City, ZipCode, Country, Email, Password, Phone); const url ='http://localhost:56400/api/Registration/Registration'; const data = { FirstName : FirstName, LastName : LastName, StreetAddress : StreetAddress, Apartment : Apartment, City : City, ZipCode : ZipCode, Country : Country, Email : Email, Password : Password, Phone : Phone } axios.post(url,data) .then((result) => { const dt = result.data; }) .catch((error)=>{ console.log(error); }) } return( <div> <UserNavBar /> <section class="vh-200"> <div class="container-fluid"> <img class= "mindBody" src={EWholism_Image2} alt="EWholism_Image2" /> <div class="row"></div> <div class="col-sm-7 text-black"> <div class="px-5 ms-xl-4"> <i class="fas fa-crow fa-2x me-3 pt-5 mt-xl-4" style={{color: "#709085"}}></i> <span class="h1 fw-bold mb-0">Logo</span> </div> <div class="d-flex align-items-center h-custom-2 px-5 ms-xl-4 mt-5 pt-5 pt-xl-0 mt-xl-n5"> <form style={{width: "23rem"}}> <h3 class="fw-normal mb-5" style={{color: "#4835d4"}}>Register Here</h3> <div class="form-outline"> <input type="text" class="form-control form-control-lg" onChange={(e) => setFirstName(e.target.value)} /> <label class="form-label" for="FirstName">First name</label> </div> <div class="form-outline"> <input type="text" class="form-control form-control-lg" onChange={(e) => setLastName(e.target.value)} /> <label class="form-label" for="LastName">Last name</label> </div> <div class="form-outline form-white"> <input type="text" class="form-control form-control-lg" onChange={(e) => SetStreetAddress(e.target.value)} /> <label class="form-label" for="StreetAddress">Street Address</label> </div> <div class="form-outline form-white"> <input type="text" class="form-control form-control-lg" onChange={(e) => setApartment(e.target.value)} /> <label class="form-label" for="Apartment">Apartment/Suit #</label> </div> <div class="form-outline form-white"> <input type="text" class="form-control form-control-lg" onChange={(e) => setCity(e.target.value)} /> <label class="form-label" for="City">City</label> </div> <div class="form-outline form-white"> <input type="text" class="form-control form-control-lg" onChange={(e) => setZipCode(e.target.value)} /> <label class="form-label" for="ZipCode">Zip Code</label> </div> <div class="form-outline form-white"> <input type="text" class="form-control form-control-lg" onChange={(e) => setCountry(e.target.value)} /> <label class="form-label" for="Country">Country</label> </div> <br /> <div class="form-outline form-white"> <input type="text" class="form-control form-control-lg" onChange={(e) => setPhone(e.target.value)} /> <label class="form-label" for="Phone">Phone Number</label> </div> <div class="form-outline form-white"> <input type="text" class="form-control form-control-lg" onChange={(e) => setEmail(e.target.value)} /> <label class="form-label" for="Email">Your Email</label> </div> <div class="form-outline form-white"> <input type="text" class="form-control form-control-lg" onChange={(e) => setPassword(e.target.value)} /> <label class="form-label" for="Password">Create a passowrd..</label> </div> <div class="pt-1 mb-4"> <button onClick={(e) => handleSave(e)}>Register</button> </div> </form> </div> </div> </div> </section> </div> ) } export default Registration;
排查方向
- 端口与路由匹配:确认后端实际运行的端口是否为56400,可在VS 2019的项目属性→调试中检查应用URL。
- 路由有效性测试:用Postman直接调用
http://localhost:56400/api/Registration/Registration,若仍返回404,说明后端路由配置或控制器存在问题。 - 模型绑定校验:前端
ZipCode和Phone输入为文本类型,但后端模型对应字段是int类型,若输入非数字会导致绑定失败;可将后端对应字段改为string,或前端input改为number类型并添加输入校验。 - CORS配置细节:确认后端CORS是否允许前端所在的源(通常前端运行端口为3000),可临时配置允许所有源测试:
services.AddCors(options => { options.AddPolicy("AllowAll", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); // 在Configure方法中启用 app.UseCors("AllowAll"); - 网络环境稳定性:
ERR_NETWORK_CHANGED多与网络切换有关,测试时保持网络稳定,避免WiFi与有线网络切换。 - 表单提交逻辑优化:给form标签添加
onSubmit={handleSave},替代仅在按钮绑定点击事件,避免默认表单提交行为干扰。
内容的提问来源于stack exchange,提问作者Lisank
相关产品推荐
相关产品推荐

