事件回顧
最近,一個一直使用的前后端分離項目部署到某環境時突然報跨域了。首先肯定想到是后端問題。后端用NetCore項目作為網關接收前端請求,並配置了跨域策略。
使用的跨域策略:
services.AddCors(options =>
options.AddPolicy("AllowSameDomain",
builder => builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials())
);
app.UseCors("AllowSameDomain");
報錯:HttpRequest at 'xxx' from origin 'xxx' has been blocked by CORS policy: 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'.
問題解決
網上查閱發現:
前端使用了 withCredentials: true,而恰恰這個使用是不允許AllowAnyOrigin()的,意思就是不允許返回的Access-Control-Allow-Origin:*。
於是將跨域策略改為:
app.UseCors(builder =>
{
builder.SetIsOriginAllowed(_ => true)
.AllowCredentials()
.AllowAnyHeader();
});
不再報錯