您的代码似乎工作得很好,并且确实成功地发送了以前的和新的头文件.罪魁祸首是选项withCredentials: true
,它导致以下错误:
在‘https://example.com’From Origin‘http://localhost:4200’上访问XMLHttpRequest的权限
已被CORS策略阻止:对印前判断请求的响应不
通过访问控制判断:The value of the
'Access-Control-Allow-Origin' header in the response must not be the
wildcard '*' when the request's credentials mode is 'include'.这个
XMLHttpRequest发起的请求的凭据模式为
由with Credentials属性控制.
如错误所示,服务器可能在飞行前判断(OPTIONS请求的响应)中发送标头Access-Control-Allow-Origin: *
.只有当服务器发送标头Access-Control-Allow-Origin: http://localhost:4200 (or whatever your origin is)
时,您的请求才会起作用.
不能同时使用Access-Control-Allow-Origin: *
和withCredentials: true
的原因解释如下:CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true
我创建了一个后端来重现这个问题.执行以下步骤将解决您的问题:
- 将
http://localhost:4200
(或您的原点)添加到允许CORS原点列表(不能将其设置为*
).
- 通过将
access-control-allow-headers
设置为*
,允许将自定义头传递到您的后端.
- 将CORS设置中的
allow_credentials
设置为true
.
如果您使用的是Python(快速API),则可以这样进行上述设置(已测试并正常工作):
app = FastAPI()
origins = [
"http://localhost:4200"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
如果您使用的是.NET Core,则可以执行以下设置(未经测试):
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
policy =>
{
policy.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.MapControllers();
app.Run();
也要在IIS上进行类似的设置(如果您使用的是IIS).
allowCredentials="true"
个
allowAllRequestedHeaders="true"
个
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<cors enabled="true" failUnlistedOrigins="true">
<add origin="http://localhost:4200"
allowCredentials="true"
maxAge="120">
<allowHeaders allowAllRequestedHeaders="true">
<add header="Demo" />
</allowHeaders>
<allowMethods>
<add method="DELETE" />
<add method="GET" />
<add method="POST" />
<add method="PUT" />
<add method="OPTIONS" />
</allowMethods>
</add>
</cors>
</system.webServer>
</configuration>