Click here to Skip to main content
15,171,053 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am creating a demo application which is used to display person details on UI using web api and angular JS. My code is working fine if I am launching Chrome using "chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security", however it's not working for normal Chrome/IE. I did some debugging and found that seems CORS issue. I tried to enable CORS at api end as well but not working for me. Can someone please help me to make it working. Thanks in advance. Below is my code snippet:

WebAPI:
public class HomeController : ApiController
{
public HttpResponseMessage GetPersonDetails()
{
var person = new List<person>
{
new Person {Id=1, Address="Pune", Name="Test1"},
new Person {Id=2, Address="Pune", Name="Test2"},
new Person {Id=3, Address="Pune", Name="Test3"},
new Person {Id=4, Address="Pune", Name="Test4"}
};
return Request.CreateResponse(HttpStatusCode.OK, person);
}
}

angular code:
var appModule = angular.module("MyApp", []);

appModule.controller('getUserDetailsController', function ($scope, $http) {
           $http({
               method: 'GET',
               url: 'http://localhost:61896/api/Home/GetPersonDetails',
               headers: {

                   'Access-Control-Allow-Headers': '*',
                   'Access-Control-Allow-Methods': '*',
                   'Access-Control-Allow-Origin': '*'

               },
               contentType:'text/plain; charset=UTF-8'
           }).then(function (response) {

               $scope.objUserDetails = response.data;


           });
       });


What I have tried:

I tried to enable CORS at api end, also tried to send header from js, but nothing worked for me.
Posted
Updated 9-Jan-19 5:51am

1 solution

If you've tried to enable CORS on the API side and it didn't work out then possible reason is that you're running your page locally i.e. via file:// instead of http://
It was the case for me once and I've solved it by deploying my app using http-server package
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900