Home > Software engineering >  Cant get data (using angular) from the API (dotNet Core) No 'Access-Control-Allow-Origin'
Cant get data (using angular) from the API (dotNet Core) No 'Access-Control-Allow-Origin'

Time:10-13

Access to XMLHttpRequest at 'https://localhost:5001/api/users' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I have also tried AllowAnyOrigin(); same eror, and .SetIsOriginAllowed(origin => true)); same error as well.

Angular (app.component.ts)

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Testing SPA';
  users :any;

  constructor (private http: HttpClient) {}
  ngOnInit(){
    this.getUsers();
  }

  getUsers (){
    this.http.get('https://localhost:5001/api/users').subscribe(response => {this.users = response;},error =>{console.log(error);})
  }

}

dotNet (startup.cs)

namespace API
{
    public class Startup
    {
        private readonly IConfiguration _config;
        public Startup(IConfiguration config)
        {
            _config = config;           
        }



        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddDbContext<DataContext>(options =>
            {
                options.UseSqlite(_config.GetConnectionString("DefaultConnection"));
            });
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
            });
            
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
            }
            
            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseCors(x => x.AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials()
                .WithOrigins("http://localhost:4200"));
            app.UseAuthorization();
            
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

CodePudding user response:

Try this in ConfigureServices:

  services.AddCors(
    options =>
    {
      options.AddPolicy(
        "Any",
        cors =>
        {
            cors.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
        });
    });

and then in Configure:

app.UseCors("Any")
  • Related