我正在开发一个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控制台中收到了这个错误:
在'获取的访问权限https://localhost:5001/Api/Login'来自原点'https://localhost:3000'已被CORS策略阻止:否请求的上存在"Access Control Allow Origin"标头资源如果不透明的响应符合您的需求,请设置请求的模式设置为"no cors"以在禁用cors的情况下获取资源。
我是ASP.NET和React的新手,因此欢迎提供任何帮助或提示。如果你需要更多信息,我会编辑这个问题。
CORS是通过两个步骤添加ASP.NET的:
- 在
Startup
中添加在ConfigureServices
中完成的所需服务 - 在
Startup
中添加在Configure
中完成的CORS中间件
根据您所展示的内容,我认为您错过了步骤2。在Startup
中的Configure
方法中,应添加对UseCors()
AFTERUseRouting()
的调用。
这是关于CORS的官方页面。注意:这里的示例使用了.NET6最小api,但想法保持不变——先添加服务,然后添加中间件。
您的问题是,localhost:3000上的开发服务器正在发送cors头。
看看这里:https://create-react-app.dev/docs/proxying-api-requests-in-development/