Ensure CORS response header values are valid
網(wǎng)站上線后,后臺(tái)捕獲到很多404錯(cuò)誤,同時(shí)打開(kāi)前臺(tái),看到以下瀏覽器報(bào)警信息。
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原理:在服務(wù)器響應(yīng)報(bào)文頭中通過(guò)access-control-allow-orgin告訴瀏覽器允許跨域訪問(wèn)的域名。
參考地址:https://web.dev/cross-origin-resource-sharing/?utm_source=devtools
二、解決方案:
3.1的在
public void ConfigureServices(IServiceCollection services) { //解決 Ensure CORS response header values are valid 問(wèn)題 services.AddCors(opt => { opt.AddDefaultPolicy(b => { //允許哪些域名訪問(wèn) b.WithOrigins(new string[] { "http://www.bemnnoss.com:3000" }) //AllowAnyOrgin() 接收所有的url //AllowAnyMethod() 接受所有的傳輸方式 //AllowAnyHeader() 接受所有的報(bào)文頭 //AllowCredentials() 接收所有的認(rèn)證方式 .AllowAnyMethod().AllowAnyHeader().AllowCredentials(); }); }); }
然后
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLeftTime) { app.UseCors();//解決 Ensure CORS response header values are valid 問(wèn)題 }
1、在var app=builder.Build()前寫(xiě)入
builder.Services.AddCors(opt=>{
opt.AddDefaultPolicy(b=>{
//允許哪些域名訪問(wèn)
b.WithOrigins(new string[]{"http://localhost:3000"})
//AllowAnyOrgin() 接收所有的url
//AllowAnyMethod() 接受所有的傳輸方式
//AllowAnyHeader() 接受所有的報(bào)文頭
//AllowCredentials() 接收所有的認(rèn)證方式
.AllowAnyMethod().AllowAnyHeader().AllowCredentials();
})
})
2、在Program.cs的app.UseHttpsRedirection()這句代碼之前增加一行
app.UseCors();
官方文檔:https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-6.0