代码之家  ›  专栏  ›  技术社区  ›  Ashok kumar

无法解决Angular中的“不存在访问控制允许原始标头”问题

  •  0
  • Ashok kumar  · 技术社区  · 1 年前

    我正在尝试通过Web API连接到SQL Server数据库,并使用Angular在浏览器中显示结果。但是,我不断地低于错误。

    在“”访问XMLHttpRequesthttps://localhost:7216/api/departments'来自原点'http://localhost:4200'已被CORS策略阻止:请求的资源上不存在“Access Control Allow Origin”标头。

    以下是中的完整代码 Program.cs API项目的文件。我之所以复制完整的代码,是因为,有时放置的相关性 addCors() useCors() 也很重要。

    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());
    }
    

    以下是中的完整代码 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
    

    在谷歌搜索时,我发现 this nice article 按照这里提到的步骤走,运气不好。

    有人能告诉我哪里做错了吗!

    1 回复  |  直到 1 年前
        1
  •  0
  •   Yong Shun    1 年前

    CORS中要列入白名单的端点不正确,目前,您正在将API操作列入白名单,您需要将Angular应用程序列入白名单。

    app.UseCors(builder => builder.AllowAnyHeader()
                                .AllowAnyMethod()
                                .WithOrigins("http://localhost:4200")
    );
    

    奖金

    您应该在中设置CORS端点 appsettings.json 而不是在 程序.cs 用于处理多个环境,如开发、暂存、生产等。参考: Configuration in ASP.NET Core

    应用程序设置。{Environment}.json

    {
      "CorsOrigins": "https://localhost:4200"
    }
    

    要从中获取配置 appsettings.json :

    app.UseCors(builder => builder.AllowAnyHeader()
                                .AllowAnyMethod()
                                .WithOrigins(builder.Configuration["CorsOrigins"])
    );