4

Here I'm using an HTTP POST request from Angular 6 and it is hitting in the .net core Web API call, but I'm not getting the response output back to Angular 6 and in console got an error that:

"Access to XMLHttpRequest at 'http://localhost:55654/api/login/auth' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

But I'm a bit confused that if it is any CORS enabling access issue, it won't hit the web API call. But it hits the API call and I'm not getting the response back.

Angular 6 HTTP POST request:

this.http.post("http://localhost:55654/api/login/auth", credentials, {
  headers: new HttpHeaders({
 "Content-Type": "application/json"
      })
  }).subscribe(response => {
      let token = (<any>response);
      localStorage.setItem("jwt", token);
    }, err => {

    });

I've enabled the CORS in following methods in .NetCore Web API

Configure Method in Startup.cs:

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

ConfigureServices Method in Startup.cs:

...
services.AddCors();
...
2
  • 1
    Is app.UseMvc called before or after app.UseCors? It needs to be AFTER app.UseCors
    – UncleDave
    Commented May 16, 2019 at 12:11
  • This works....Thank you
    – Haritha Es
    Commented May 17, 2019 at 5:01

3 Answers 3

6

On Startup.cs add in ConfigureServices:

services.AddCors();

On Configure add

app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

This solved your problem

1
  • Why would this make a difference considering the OP's code snippet from Startup.cs?
    – UncleDave
    Commented May 16, 2019 at 12:10
3

As mentioned in the comments:

The call to app.UseMvc needs to be AFTER app.UseCors

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

app.UseMvc();
...
1

I would suggest to add a Proxy to access your Backend. Just add an proxy-file (proxy.conf.json) to your root directory.

Serve your App with: ng s --proxy-config [PathToProxy]

For example:

{
  "/api/*": {
    "target": "http://localhost:55654",
    "secure": false,
    "logLevel": "debug"
  }
}

https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.