ERROR: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I'm working with ASP.NET Core 3.1 and Angular 8
In Angular code, I created a service to communicate with server-side by HttpClient but I always receive an error instead of getting an array of products.
Access to XMLHttpRequest at 'https://localhost:5001/api/products' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here is my Angular code
export class ProductService {
constructor(private client: HttpClient) {}
public GetProducts(): Observable<Product[]>{
return this.client.get<Product[]>("https://localhost:5001/api/products");
}
}
export interface Product
{
Id : number,
Name: string,
Price : number,
CreatedDate : Date,
Quantity : number
}
Actually, I can get data with the same URL by using browser but I can't work by Angular project
I don't know the issue comes from the Angular Project or ASP.NET Core project.
-
S0
Sandeep Kumar Dec 29 2020
It's not an issue. It's security feature of .NET Core to secure your API which called by allow origin.
To allow Angular project call http to ASP.NET Core application. You can config CORS for your ASP.NET Core project.
In
Startup.cs
, you have to add new CORS policy to override default policyservices.AddCors(setup => { setup.AddPolicy("AngularLocalPolicy", config => { config.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod(); }); });
Don't forget to use the new policy in
Configure
methodapp.UseCors("AngularLocalPolicy");
You can find more information about CORS Here
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.