每当我从我制作的前端网页向服务器发送发布请求时,开发工具控制台都会抛出以下错误:
Access to fetch at 'http://127.0.0.1:5000/CreateBooking' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
这是我的程序.cs:
using Microsoft.AspNetCore.HttpOverrides;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers().AddNewtonsoftJson();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("http://127.0.0.1:5500")
.AllowAnyHeader().AllowAnyMethod();
}
);
});
builder.WebHost.UseUrls("http://*:5000");
var app = builder.Build();
app.UseCors();
app.UseStaticFiles();
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto
});
app.UseAuthorization();
app.MapControllers();
app.Run();
要发布即时消息,只需使用带标题的 fetch:“Content-Type”:“application/json”
我尝试过使用通配符来源:
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("*")
.AllowAnyHeader().AllowAnyMethod();
}
);
});
但是我仍然遇到同样的错误。我想知道我的构建者是否没有应用该策略,或者我设置策略的方式是否存在本质上的错误。任何帮助将不胜感激,因为这是我的第一个成熟的应用程序并且
来自 CORS 以及命名策略和中间件,
使用端点路由,必须将 CORS 中间件配置为在对 UseRouting 和 UseEndpoints 的调用之间执行。
app.UseForwardedHeaders()
,你的中间件管道(结构)应该是:
var app = builder.Build();
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto
});
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.MapControllers();
app.Run();