ASP.NET Core+React测验应用登录页Axios网络错误排查求助
问题描述
我在Visual Studio 2022中使用ASP.NET Core和React.js模板开发测验应用,登录表单提交时持续触发AxiosError,错误信息为'Network Error',错误代码'ERR_NETWORK'。已尝试配置CORS,但问题依旧。
登录组件代码
import React from 'react'; import { Button, Card, CardContent, TextField, Typography } from '@mui/material'; import { Box } from '@mui/system'; import Center from './Center'; import useForm from '../hooks/useForm'; import { ENDPOINTS, createAPIEndpoint } from '../api'; const getFreshModel = () => ({ name: '', email:'', }) export default function Login() { const { values, errors, setErrors, handldeInputCahange } = useForm (getFreshModel); const login = e => { e.preventDefault(); if (validate()) { createAPIEndpoint(ENDPOINTS.participant) .post(values) .then(res => console.log(res)) .catch(err => console.log(err)); } } const validate = () => { let temp = {} temp.email = (/\S+@\S+\.\S+/).test(values.email) ? "" : "Email is not valid" temp.name = values.name !== "" ? "" : "This field is required." setErrors(temp) return Object.values(temp).every(x => x ==="") } return ( <Center> <Card sx={{width:400}}> <CardContent sx={{textAlign:'center'}} > <Typography variant="h3" sx={{ marginY: 3 }}> Driving Test App </Typography> <Box sx={{ ' & .MuiTextField-root':{ margin: 1, width: '90%' } }}> <form noValidate autoComplete='on' onSubmit={login}> <TextField label="Email" name="email" value={values.email} onChange={handldeInputCahange} variant="outlined" {...(errors.email && { error:true, helperText: errors.email } )} /> <TextField label="Name" name="name" value={values.name} onChange={handldeInputCahange} variant="outlined" {...(errors.name&& { error:true, helperText: errors.name } )} /> <Button type="submit" variant="contained" size="large" sx={{width:'90'}}>Start</Button> </form> </Box> </CardContent> </Card> </Center> ) }
API配置代码(Index.js)
import axios from 'axios'; export const BASE_URL = 'https://localhost:44421/'; export const ENDPOINTS = { participant: 'participant' } export const createAPIEndpoint = endpoint => { let url = BASE_URL + 'api/' + endpoint + '/'; return { fetch: () => axios.get(url), fetchById: id => axios.get(url + id), post: newRecord => axios.post(url, newRecord), put: (id, updatedRecord) => axios.put(url + id, updatedRecord), delete: id => axios.delete(url + id), } }
后端ParticipantController代码
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Driving_Test_Web_App.Models; using Microsoft.AspNetCore.Cors; namespace Driving_Test_Web_App.Controllers { [Route("api/[controller]")] [ApiController] public class ParticipantController : ControllerBase { private readonly ApplicationDbContext _context; public ParticipantController(ApplicationDbContext context) { _context = context; } // GET: api/Participant [HttpGet] public async Task<ActionResult<IEnumerable<Participant>>> GetParticipants() { if (_context.Participants == null) { return NotFound(); } return await _context.Participants.ToListAsync(); } // GET: api/Participant/5 [HttpGet("{id}")] public async Task<ActionResult<Participant>> GetParticipant(int id) { if (_context.Participants == null) { return NotFound(); } var participant = await _context.Participants.FindAsync(id); if (participant == null) { return NotFound(); } return participant; } // PUT: api/Participant/5 [HttpPut("{id}")] public async Task<IActionResult> PutParticipant(int id, Participant participant) { if (id != participant.ParticipantId) { return BadRequest(); } _context.Entry(participant).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ParticipantExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Participant [EnableCors("Policy")] [HttpPost] public async Task<ActionResult<Participant>> PostParticipant(Participant participant) { var temp = _context.Participants .Where(x => x.Name == participant.Name && x.Email == participant.Email) .FirstOrDefault(); if (temp == null) { _context.Participants.Add(participant); await _context.SaveChangesAsync(); } else participant = temp; return Ok(participant); } // DELETE: api/Participant/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteParticipant(int id) { if (_context.Participants == null) { return NotFound(); } var participant = await _context.Participants.FindAsync(id); if (participant == null) { return NotFound(); } _context.Participants.Remove(participant); await _context.SaveChangesAsync(); return NoContent(); } private bool ParticipantExists(int id) { return (_context.Participants?.Any(e => e.ParticipantId == id)).GetValueOrDefault(); } } }
排查与解决步骤
确认后端服务状态
- 检查ASP.NET Core项目是否已启动,且运行端口为
44421。直接在浏览器访问https://localhost:44421/api/Participant,如果无法返回数据,说明后端服务未正常运行,先解决启动问题。
- 检查ASP.NET Core项目是否已启动,且运行端口为
补全CORS配置
你仅在PostParticipant方法上添加了[EnableCors("Policy")],但未在全局配置CORS策略。需要在Program.cs中添加以下代码:var builder = WebApplication.CreateBuilder(args); // 配置CORS策略 builder.Services.AddCors(options => { options.AddPolicy("Policy", policy => { policy.WithOrigins("http://localhost:3000") // 替换为你的React应用实际端口 .AllowAnyHeader() .AllowAnyMethod(); }); }); // 其他服务注册... var app = builder.Build(); // 在路由前启用CORS中间件 app.UseCors("Policy"); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();确保React应用的端口与
WithOrigins中的地址一致。检查API URL一致性
你的API生成的URL是https://localhost:44421/api/participant/,但后端Controller路由是api/Participant(首字母大写)。虽然ASP.NET Core路由不区分大小写,但建议统一命名,避免潜在问题,比如将ENDPOINTS中的participant改为Participant。处理HTTPS证书问题
本地开发时,ASP.NET Core的自签名HTTPS证书可能不被信任,导致Axios请求失败:- 先在浏览器访问
https://localhost:44421,手动接受不安全连接后再测试表单提交; - 或在React项目的
package.json中添加代理配置:"proxy": "https://localhost:44421",让请求通过代理转发,绕过证书和跨域问题。
- 先在浏览器访问
排查Axios请求细节
在catch中打印更详细的错误信息:.catch(err => { console.log('错误详情:', err.response, err.request, err.message); });查看是否有请求头异常、请求未发送等细节问题。
内容的提问来源于stack exchange,提问作者Simbarashe Nyaruwata
相关产品推荐
相关产品推荐

