Ensure CORS response header values are valid
網(wǎng)站上線后,后臺捕獲到很多404錯誤,同時打開前臺,看到以下瀏覽器報警信息。
Ensure CORS response header values are valid
A cross-origin resource sharing (CORS) request was blocked because of invalid or missing response headers of the request or the associated preflight request .To fix this issue, ensure the response to the CORS request and/or the associated preflight request are not missing headers and use valid header values.
Note that if an opaque response is sufficient, the request's mode can be set to no-cors to fetch the resource with CORS disabled; that way CORS headers are not required but the response content is inaccessible (opaque)
一、CORE原理:在服務器響應報文頭中通過access-control-allow-orgin告訴瀏覽器允許跨域訪問的域名。
參考地址:https://web.dev/cross-origin-resource-sharing/?utm_source=devtools
二、解決方案:
3.1的在
public void ConfigureServices(IServiceCollection services) { //解決 Ensure CORS response header values are valid 問題 services.AddCors(opt => { opt.AddDefaultPolicy(b => { //允許哪些域名訪問 b.WithOrigins(new string[] { "http://www.maiyt.com:3000" }) //AllowAnyOrgin() 接收所有的url //AllowAnyMethod() 接受所有的傳輸方式 //AllowAnyHeader() 接受所有的報文頭 //AllowCredentials() 接收所有的認證方式 .AllowAnyMethod().AllowAnyHeader().AllowCredentials(); }); }); }
然后
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLeftTime) { app.UseCors();//解決 Ensure CORS response header values are valid 問題 }
1、在var app=builder.Build()前寫入
builder.Services.AddCors(opt=>{
opt.AddDefaultPolicy(b=>{
//允許哪些域名訪問
b.WithOrigins(new string[]{"http://localhost:3000"})
//AllowAnyOrgin() 接收所有的url
//AllowAnyMethod() 接受所有的傳輸方式
//AllowAnyHeader() 接受所有的報文頭
//AllowCredentials() 接收所有的認證方式
.AllowAnyMethod().AllowAnyHeader().AllowCredentials();
})
})
2、在Program.cs的app.UseHttpsRedirection()這句代碼之前增加一行
app.UseCors();
官方文檔:https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-6.0