CORS – Cross-Origin Resource Sharing
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin.
If you are not that familiar with CORS read about CORS first then continue with this article.
Angular runs on its own server (by default localhost:4200) and webAPI runs on a different port so we get the Cors issue.
So, from the above screen, it is clear that WebAPI is running on port 57263 and our application is running on 4599 (it's not running in 4200 as I have changed the port in package.json).
http://localhost:4599 - http://localhost:57263 (here domain is same but the port number is different - one of the rules to satisfy CORS)
So, the solution for the above issue is,
- Angular proxy (client-side solution)
- Enable CORS on the webAPI (Server Side)
In this article, we will see a detailed explanation on how to use Angular Proxy only. This example is created using Angular CLI version 6.
Step 0
Create a .NETWebAPI with the below sample methods.
Step 1
Create an AngularCLI Project named “AngularProxyApp”
Step 2
Create the Service File and all the Code for Service Call.
Step 3
Call the Service from the app.component.ts
Here, only the structure and code snippets are shown, you can put it together for a proxy shows.
Project structure