ASP.NET 核心 API 无法从 React.js 访问
ASP.NET Core API not accessible from React.js
我正在开发一个 Web 应用程序,前端使用 React,后端使用 ASP.NET Core。
这是我 Startup.cs
的代码。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod();
});
});
}
这是我的完整 API 控制器,在 Visual Studio 2022 年使用 ISS 调试时从 Chrome 开始工作正常。
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace AsignacionesBackend.Controllers
{
[ApiController]
[Route("[controller]")]
public class ApiController : ControllerBase
{
private readonly ILogger<ApiController> _logger;
public ApiController(ILogger<ApiController> logger)
{
_logger = logger;
}
[Route("Login")]
public IActionResult Login()
{
JsonUser body = new JsonUser("hola", "buenas");
body.Token = "tokendeprueba";
JsonResult json = new JsonResult(body);
return json;
}
public class JsonUser
{
public string User { get; set; }
public string Pass { get; set; }
public string Token { get; set; }
public JsonUser(string user, string pass)
{
User = user;
Pass = pass;
}
}
}
}
这是调用 API 的 React 代码。
let result = fetch("https://localhost:5001/Api/Login");
result = await (await result).json;
console.log(result);
我在执行 React 代码时在 Chrome 控制台中收到此错误:
Access to fetch at 'https://localhost:5001/Api/Login' from origin
'https://localhost:3000' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
我是 ASP.NET 和 React 的新手,所以欢迎提供任何帮助或提示。如果您需要更多信息,我会编辑问题。
你的问题是,你在 localhost:3000 上的开发服务器正在发送一个 cors header。
看这里:https://create-react-app.dev/docs/proxying-api-requests-in-development/
CORS 是 ASP.NET 分两步添加:
- 在
Startup
中添加在 ConfigureServices
中完成的所需服务
- 在
Startup
中添加在Configure
中完成的CORS中间件
根据您展示的内容,我假设您错过了第 2 步。在 Startup
中的 Configure
方法中,您应该添加对 UseCors()
AFTER UseRouting()
.
的调用
Here 是关于 CORS 的官方页面。注意:那里的示例使用的是 .NET 6 minimal api,但想法保持不变 - 添加服务然后添加中间件。
我正在开发一个 Web 应用程序,前端使用 React,后端使用 ASP.NET Core。
这是我 Startup.cs
的代码。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod();
});
});
}
这是我的完整 API 控制器,在 Visual Studio 2022 年使用 ISS 调试时从 Chrome 开始工作正常。
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace AsignacionesBackend.Controllers
{
[ApiController]
[Route("[controller]")]
public class ApiController : ControllerBase
{
private readonly ILogger<ApiController> _logger;
public ApiController(ILogger<ApiController> logger)
{
_logger = logger;
}
[Route("Login")]
public IActionResult Login()
{
JsonUser body = new JsonUser("hola", "buenas");
body.Token = "tokendeprueba";
JsonResult json = new JsonResult(body);
return json;
}
public class JsonUser
{
public string User { get; set; }
public string Pass { get; set; }
public string Token { get; set; }
public JsonUser(string user, string pass)
{
User = user;
Pass = pass;
}
}
}
}
这是调用 API 的 React 代码。
let result = fetch("https://localhost:5001/Api/Login");
result = await (await result).json;
console.log(result);
我在执行 React 代码时在 Chrome 控制台中收到此错误:
Access to fetch at 'https://localhost:5001/Api/Login' from origin 'https://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我是 ASP.NET 和 React 的新手,所以欢迎提供任何帮助或提示。如果您需要更多信息,我会编辑问题。
你的问题是,你在 localhost:3000 上的开发服务器正在发送一个 cors header。
看这里:https://create-react-app.dev/docs/proxying-api-requests-in-development/
CORS 是 ASP.NET 分两步添加:
- 在
Startup
中添加在 - 在
Startup
中添加在
ConfigureServices
中完成的所需服务
Configure
中完成的CORS中间件
根据您展示的内容,我假设您错过了第 2 步。在 Startup
中的 Configure
方法中,您应该添加对 UseCors()
AFTER UseRouting()
.
Here 是关于 CORS 的官方页面。注意:那里的示例使用的是 .NET 6 minimal api,但想法保持不变 - 添加服务然后添加中间件。