Angular中无法解决“No Access-Control-Allow-Origin header is present”问题
问题
尝试通过Web API连接SQL Server数据库,并用Angular在浏览器展示数据时,反复出现CORS拦截错误:
Access to XMLHttpRequest at 'https://localhost:7216/api/departments' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
API项目Program.cs完整代码
Log.Logger = new LoggerConfiguration() .MinimumLevel.Warning() .WriteTo.Console() .WriteTo.File("logs/Log_Of_Practice.txt", rollingInterval: RollingInterval.Day) .CreateLogger(); var builder = WebApplication.CreateBuilder(args); builder.Host.UseSerilog(); // Add services to the container. ApplicationServices(builder.Services, builder.Configuration); builder.Services.AddScoped<IDepartmentRepository, DepartmentRepository>(); builder.Services.AddScoped<IExampleService, ExampleService>(); builder.Services.AddCors(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseCors(builder => builder.AllowAnyHeader() .AllowAnyMethod() .WithOrigins("https://localhost:7216/api/departments/") ); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => endpoints.MapControllers()); app.MapControllers(); app.Run(); static void ApplicationServices(IServiceCollection services, IConfiguration configuration) { services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle services.AddEndpointsApiExplorer(); services.AddSwaggerGen(); services.AddSingleton<EmployeeDataStore>(); services.AddDbContext<CompanyContext>(x => x.UseSqlite(configuration["ConnectionStrings:PracticeDbConnectionString"])); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); }
Angular项目app.component.ts完整代码
export class AppComponent implements OnInit { title = 'Angular Learnings - Show All Departments'; departments: any; successState = true; constructor(private http: HttpClient) { } ngOnInit() { this.http.get('https://localhost:7216/api/departments').subscribe({ next: response => { this.successState = true; this.departments = response; }, error: error => { this.successState = false; console.log(error); }, complete: () => { if(this.successState) { console.log('Request was processed successfully'); } else if(!this.successState) { console.log('Request was unable to process successfully. See log for more details'); } } }); } }
app.component.html代码
<div class="container"> {{ departments }} </div>
执行时的完整错误日志
Access to XMLHttpRequest at 'https://localhost:7216/api/departments' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. app.component.ts:25 HttpErrorResponseerror: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: 'error', …}headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}message: "Http failure response for https://localhost:7216/api/departments: 0 Unknown Error"name: "HttpErrorResponse"ok: falsestatus: 0statusText: "Unknown Error"url: "https://localhost:7216/api/departments"[[Prototype]]: HttpResponseBase :7216/api/departments:1 Failed to load resource: net::ERR_FAILED
解决方案
你的问题出在两个关键地方:
1. CORS源地址配置错误
UseCors里的WithOrigins填的是API自身的接口地址,而CORS需要授权的是发起请求的前端源地址,也就是你的Angular项目地址http://localhost:4200。
2. 中间件顺序错误
ASP.NET Core的中间件执行顺序严格,UseCors必须放在UseRouting和UseAuthorization之前,否则CORS头不会被正确添加。同时你重复配置了UseEndpoints和MapControllers,保留一个即可。
修改后的Program.cs关键代码
var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); // 调整UseCors到正确位置,修改源地址 app.UseCors(builder => builder.AllowAnyHeader() .AllowAnyMethod() .WithOrigins("http://localhost:4200") ); app.UseRouting(); app.UseAuthorization(); // 保留一个路由映射即可 app.MapControllers(); app.Run();
修改完成后,重启你的API服务,再重新运行Angular项目即可解决CORS问题。
内容的提问来源于stack exchange,提问作者Ashok kumar
相关产品推荐
相关产品推荐

