在上一篇會發現跑出來沒有存取成功
開啟console會觀察到有出現
違反同源政策的error訊息
Access to XMLHttpRequest at 'https://localhost:7247/api/product' from origin 'https://localhost:44481' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
就Browser而言有所謂的同源政策
白話來說也就是同一個網站內的程式資源可互相存取訪問,但若不同則禁止訪問。
比方不同domain name
http://abc.com跟http://def.com
或同domain name但不同port的
http://localhost:3500 跟 http://localhost:3800
皆為非同源的實際案例
這裡可以於Startup.cs中開啟Cors機制
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCors(options =>
{
options.AddPolicy("any", builder =>
{
//允許任何不同來源的站台應用存取
builder.SetIsOriginAllowed(_ => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors("any");
app.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html"); ;
app.Run();
即可調整CORS限制的問題