Angular 4 is great and comes loaded with more features. You might be wondering why Angular 3 was skipped. They made it this way to unify all Angular components with the Angular Router (already developed up to version 3) which had to be upgraded to v4. So, Angular 4 was the chosen name to mean the entire Angular Framework.
Okay with that interesting information, let me come straight to the topic. Once you start working with Angular applications, you might run into issues while calling API’s. Making API calls from Angular application using HTTP service of Angular framework gives you issues.
In Angular, every API call you make is an AJAX jQuery call. You might not face such issues with the API calls made from pure C# code.
Here is what you will encounter:
No 'Access-Control-Allow-Origin' header is present on the requested resource – Angular4 .Net core API calls.
When you get this kind of issue, the hit goes to API server and while returning the response it was not able to send the result without the proper header.
How to solve the Angular 4 API call issue?
In Visual Studio 2017 – you can enable the Enable SSL property, by following below steps.
- Right click on your project and choose Properties from the context menu.
- Go to Debug tab, under Web Server settings which will look like below
Make sure the Enable SSL property is checked.
Next, you must setup CORS policy in your API, it is a three step process as given below
- Register CORS functionality
- Configure CORS options
- Apply the functionality
Open your .Net core project and go to Startup.cs file where we are going to cover the above three steps.
Place the below code under ConfigureServices method to register and configure the CORS policy
corsPolicyBuilder => corsPolicyBuilder.AllowAnyOrigin()
// Apply CORS policy for any type of origin
// Apply CORS policy for any type of http methods
// Apply CORS policy for any headers
// Apply CORS policy for all users
Then under the Configure method use the below code to apply the CORS policy. Make sure to declare the CORS functionality before MVC so the middleware fires before the MVC gets control.
If you want to apply CORS policy only for specific controllers, you can achieve that by removing the above code from Configure method and add it in the controller like below.
public class DefaultController : Controller
Important Note: In the all three-code sections shown above, ensure that you specify your CORS policy name and it should remain same in all three places.
Please let me know if this has helped you. I would be happy if it did. I will keep sharing my Angular 4 experiences in our blog. Feel free to reach out to me if you need any specific assistance. I will try to help you out.