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();
...
On Startup.cs add in ConfigureServices:
services.AddCors();
On Configure add
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
This solved your problem
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();
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With