React setupProxy无法代理自定义ASP.NET Core API控制器请求
React + ASP.NET Core API 代理404问题排查与解决
问题描述
按照官方指南搭建React Web应用与ASP.NET Core Web API两个独立项目,默认的/weatherforecast接口可正常通过代理访问,但自定义Employee控制器的请求https://localhost:3000/api/employee返回404,控制台提示无匹配路由。尝试过多种setupProxy.js的context匹配模式(如/api)均无效,相关配置代码如下:
setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function (app) { app.use( ['/api/weatherforecast', '/api/employee'], createProxyMiddleware({ target: 'https://localhost:7157', secure: false, }) ); };
Web API launchSettings.json
{ "profiles": { "WebApi": { "commandName": "Project", "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "dotnetRunMessages": true, "applicationUrl": "https://localhost:7157;http://localhost:5157" }, "IIS Express": { "commandName": "IISExpress", "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } }, "$schema": "https://json.schemastore.org/launchsettings.json", "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:34955", "sslPort": 44352 } } }
Employee控制器代码
namespace WebApi.Controllers { [ApiController] [Route("api/[controller]")] public class EmployeeController : Controller { private readonly ILogger<EmployeeController> logger; private readonly Context context; public EmployeeController(ILogger<EmployeeController> logger, TenthContext context) { this.logger = logger; this.context = context; } // GET: EmployeeController [HttpGet(Name="GetEmployee")] public IEnumerable<Employee> Get() { var employees = context.Employees.ToList(); return employees; } } }
解决步骤
1. 修正setupProxy.js代理配置
当前配置仅精确匹配两个特定路径,改为匹配所有/api前缀的请求,并添加changeOrigin参数(解决ASP.NET Core的Origin校验问题):
const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function (app) { app.use( '/api', createProxyMiddleware({ target: 'https://localhost:7157', secure: false, changeOrigin: true }) ); };
修改后重启React开发服务器,确保配置生效。
2. 修复控制器依赖注入错误
从代码中可见,控制器字段context的类型是Context,但构造函数参数传入的是TenthContext,类型不匹配会导致依赖注入失败,控制器无法初始化,最终路由不存在。修正类型一致:
// 修正字段类型为TenthContext private readonly TenthContext context; public EmployeeController(ILogger<EmployeeController> logger, TenthContext context) { this.logger = logger; this.context = context; }
3. 验证API路由可用性
启动API项目时,确保选择WebApi profile(对应端口https://localhost:7157),访问https://localhost:7157/swagger,检查是否存在/api/employee的GET接口。若Swagger中无此接口,说明控制器路由仍有问题,需确认:
[Route("api/[controller]")]注解正确,[controller]会自动映射为Employee,对应路由/api/Employee(ASP.NET Core默认路由不区分大小写,/api/employee也可访问)。Employee模型类已正确定义,且TenthContext中包含DbSet<Employee> Employees属性。
4. 确认请求路径一致性
确保React中的请求路径为/api/employee,与控制器路由匹配。
内容的提问来源于stack exchange,提问作者RamenNoodle
相关产品推荐
相关产品推荐

