我试图在前面调用一个API,但是我得到了这个错误:
Access to XMLHttpRequest at 'http://localhost:5087/api/GetPlayerById/2' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
http://localhost:3000/
上运行(React)http://localhost:5087/
(.NET 6)上我已经看过许多关于CORS政策的帖子,但似乎没有一个能帮到我。我最后一次提到的是在ASP.NET核心中启用跨源请求(CORS)。
目前为止的代码(在.NET 6中):
Program.cs
using tournament_manager_backend.Data;
using Microsoft.EntityFrameworkCore;
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
policy =>
{
policy.WithOrigins("http://localhost:3000");
});
});
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddScoped<IPlayerRepository, PlayerRepository>();
builder.Services.AddScoped<IMatchRepository, MatchRepository>();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.MapControllers();
app.Run();
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "server=(localdb)\\ProjectModels;database=TournamentManager"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Host": {
"CORS": "http://localhost:5087,http://localhost:3000"
}
}
launchSettings.json
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:19870",
"sslPort": 44328
}
},
"profiles": {
"tournament_manager_backend": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5087",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
}
}
}
}
我知道有很多关于这个话题的问题,但是我已经从不同的来源多次修改了代码,如果我在这里引用它们,它会使这个帖子太长。我尽我所能给你尽可能多的细节,以便我可以寻求有效的指导。我会感谢任何人的帮助。谢谢!
发布于 2022-09-21 19:10:34
最简单的解决方案是在用于开发的React服务器中包含一个proxy
。在您的package.json
中包括:
"proxy": "http://localhost:5087/",
作为顶级参数(即没有父级参数)的一部分。这将通过http://localhost:3000/
创建一个代理到后端。
请注意,这是为了发展。当您移动到“真正的”服务器时,您将不会使用React服务器来服务您的前端代码,并且可能会有一种不同的方式来设置CORS。
https://stackoverflow.com/questions/73805753
复制相似问题