title: Cross-Origin Request Blocked: (Reason: CORS request did not succeed)
body: <p>I'm developing a full-stack application using ASP.NET core 5.0 Web Api for the back-end and Angular 12 for the front-end.</p>
  <p>When sending a http post request to the back-end I'm getting an error related to CORS policies.</p>
  <p>The error is:</p>
  <blockquote>
  <p>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5001/api/v1/user/login. (Reason: CORS request did not succeed).</p>
  </blockquote>
  <p>I looked at this link:
  <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSDidNotSucceed" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSDidNotSucceed</a>, but it did not give me enough information to come up with the solution</p>
  <p>I believe my problem might be related to the first bullet point:</p>
  <blockquote>
  <p>Trying to access an https resource that has an invalid certificate will cause this error</p>
  </blockquote>
  <p>because my front end uses http protocol and my backend uses https protocol.</p>
  <p>What is considered a valid certificate?</p>
  <p>I also do not have an adblocker installed in my web browser so I can't think of anything else to try as I believe I am enabling CORS in my following code.</p>
  <p>Any ideas as to what is going wrong? I could be missing some sort of configuration or something?</p>
  <hr />
  <h2>Code samples</h2>
  <p><strong>Back-end</strong></p>
  <p><em>startup.cs</em></p>
  <pre><code>// startup.cs
  using MyApi.Installers;
  
  using Microsoft.AspNetCore.Builder;
  using Microsoft.AspNetCore.Hosting;
  using Microsoft.Extensions.Configuration;
  using Microsoft.Extensions.DependencyInjection;
  using Microsoft.Extensions.Hosting;
  
  namespace MyApi
  {
      public class Startup
      {
  
          public Startup(IConfiguration configuration) =&gt; Configuration = configuration;
  
          public IConfiguration Configuration { get; }
  
          // This method gets called by the runtime. Use this method to add services to the container.
          public void ConfigureServices(IServiceCollection services)
          {
              // CORS CONFIGURED HERE           
              services.AddCors(options =&gt;
              {
                  options.AddPolicy(&quot;CorsApi&quot;,
                      builder =&gt; builder.WithOrigins(&quot;http://localhost:4200&quot;)
                  .AllowAnyHeader()
                  .AllowAnyMethod());
              });
  
              // This is an extension method that installs swagger, jwt, services, etc...
              // I can add those also if need be
              services.InstallServicesInAssembly(Configuration);
          }
  
          // 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();
              }
  
              SwaggerOptions swaggerOptions = new SwaggerOptions();
              Configuration.GetSection(nameof(SwaggerOptions)).Bind(swaggerOptions);
  
              app.UseSwagger(options =&gt; options.RouteTemplate = swaggerOptions.JsonRoute);
              app.UseSwaggerUI(options =&gt;
              {
                  options.SwaggerEndpoint(swaggerOptions.UiEndpoint, swaggerOptions.Description);
                  options.RoutePrefix = System.String.Empty;
              });
  
              app.UseHttpsRedirection();
              app.UseStaticFiles();
  
              app.UseRouting();
  
              // CORS ENABLED HERE
              app.UseCors(&quot;CorsApi&quot;);
  
              app.UseAuthorization();
  
              app.UseEndpoints(endpoints =&gt; endpoints.MapControllers());
          }
      }
  }
  </code></pre>
  <p><em>UserController.cs -&gt; Login function</em></p>
  <pre><code>// UserController.cs -&gt; Login function
          [HttpPost(ApiRoutes.User.Login)]
          public IActionResult Login([FromBody] UserLoginRequest request)
          {
              if (!ModelState.IsValid)
              {
  
                  return BadRequest();
              }
  
              // Validates users credentials
              if (!_userService.IsValidUserCredentials(request.Email, request.Password))
              {
                  return Unauthorized();
              }
  
              return Ok(});
          }
  </code></pre>
  <p><strong>Front-end</strong></p>
  <p><em>auth-service.ts</em></p>
  <pre><code>// auth.service.ts
  export class AuthService {
  
    private readonly baseUrl = 'https://localhost:5001/api/v1';
  
    // Adds CORS header to the request?
    private httpOptions = { headers: new HttpHeaders({ 'Content-Type':'application/json','Access-Control-Allow-Origins':'*'})};
  
    constructor(
      private http: HttpClient
    ) { }
  
    login(email: string, password: string): Observable&lt;any&gt; {
      let postData = new FormData();
      postData.append('email', email);
      postData.append('password', password);
  
      return this.http.post&lt;any&gt;(`${this.baseUrl}/user/login`, postData, this.httpOptions);
    }
  }
  </code></pre>
  <p><em>login.component.ts</em></p>
  <pre><code>// login.component.ts
  export class LoginComponent implements OnInit {
    loginForm = this.fb.group({
      email: ['', Validators.compose([Validators.email, Validators.required])],
      password: ['', Validators.required]
    });
  
    constructor(
      private authService: AuthService,
      private router: Router,
      private fb: FormBuilder,
    ) { }
  
    ngOnInit(): void { }
  
    get f() {
      return this.loginForm.controls;
    }
  
    login(form: FormGroup): void {
      // These output in console window
      console.log(this.f.email.value);
      console.log(this.f.password.value);
  
      // Error here
      this.authService.login(this.f.email.value, this.f.password.value).subscribe(
        response =&gt; {
          // This does not get output
          console.log(response);
          //this.router.navigate(['/home']);
        },
        error =&gt; console.log(error)
      );
    }
  
  }
  </code></pre>
  <hr />
  <p>I've tried to make the code as simple as possible.</p>
  <p>Edit: forgot to mention I've also enabled this:
  <a href="https://i.stack.imgur.com/7sxzc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7sxzc.png" alt="enter image description here" /></a></p>