Reputation: 215
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();
...
Upvotes: 4
Views: 8178
Reputation: 7188
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();
...
Upvotes: 3
Reputation: 490
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
Upvotes: 1
Reputation: 1216
On Startup.cs add in ConfigureServices:
services.AddCors();
On Configure add
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
This solved your problem
Upvotes: 6