Search code examples
angularjsasp.net-web-api

$http get call with AngularJS my API is not working


I am creating a Web Application. I have created an API and when I try to make an http get call from angular, it fails. I know that my api works because I have already tested it on the browser and Postman (On Chrome). In addition, I know that my code is good because I tested it by changing the url to githubs's api (https://api.github.com/users), and the response was successful. Can anyone can help me figure out why the calls to my API don't work if both return the same (a collection of JSon objects)?

$http({
        method: 'GET',
        url:'http://localhost:63473/api/posts' // my api
        //url: 'https://api.github.com/users' // github api
    })
        .then(function (response) {

            // successful call
            angular.copy(response.data, viewModel.posts);
            alert("Good");

        }, function (error) {

            // call to api failed
            viewModel.errorMessage = "Failed to load posts: " + error;

        });

This is the response of my call from Postman

[
{
   "id": "6db78556-c4dc-4c7c-a969-db0d202f32fc",
   "text": "This is the second Post.",
   "postedOn": "2016-04-30T21:26:56.7886027-04:00"
},
{
   "id": "5c9d9e0b-0b23-4895-93ba-b86a36e03f84",
   "text": "Hello everyone, this is my first Post",
   "postedOn": "2016-04-30T21:26:56.7846017-04:00"
}
]

Solution

  • Are you running the API and the $http JS on the same URL? If they are not (even if the port is different), then you need to enable CORS on your API to allow cross domain requests.