![](/img/trans.png)
[英]CORS No 'Access-Control-Allow-Origin' header is present on the requested resource
[英]No 'Access-Control-Allow-Origin' header is present on the requested resource when 401 response is returned from the server
我有一個 .NET Core 3.0 和 Angular 8 web 應用程序。 我在 Startup.cs 中啟用了 CORS 並且工作正常。 我正在使用 JWT 身份驗證以及 angular 側的攔截器到 append Z1D1FADBD9150349C135D令牌到每個請求的 append Z1D1FADBD9150349C135FEE1781。 當令牌有效時,調用具有[Authorize]
屬性的路由成功。 當令牌過期/無效時,服務器按預期返回 401。 但是,angular 攔截器無法識別 401 錯誤,因為控制台錯誤中出現了 CORS 問題:
Access to XMLHttpRequest at ' https://localhost:5001/api/Users/test ' from origin ' http://localhost:4200 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present在請求的資源上。
在檢查響應時,我可以看到響應中沒有Access-Control-Allow-Origin
標頭。 為什么會這樣? 請注意,如果令牌有效,則不會發生這種情況。
啟動.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors(builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Angular 收到錯誤狀態為status: 0, statusText: "Unknown Error"
。
UseCors
應該放在UseAuthentication
和UseAuthorization
:
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
否則,當授權中間件使管道短路時,CORS 中間件將不會運行,因此不會添加 CORS 標頭。 這在 ASP.NET Core 3.0 中與UseAuthorization
的引入略有不同,但中間件排序一直很重要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.