0

The server sending JSON to the API is a Tomcat server in the Gradle packages (it is built in Java).

I am having trouble's making an API call with Angular. I know my API is working because I can view it on "Postman."

 var app = angular.module("todo", []);
 app.controller("AppCtrl", function($http){

 $http.get("192.168.5.100:8080/aggregators/datafile")
    .success(function(data){
        console.log(data)
    })

})

When I run it I get the following error:

XMLHttpRequest cannot load %3192.168.5.100:8080/aggregators/datafile. Cross origin requests are only supported for HTTP. 
Sleep Deprived Bulbasaur
  • 2,368
  • 4
  • 21
  • 33

1 Answers1

1

The problem you're running into is that you can't make cross origin requests from the browser without CORS or using JSONP.

Postman operates outside of the context of the browser (as if you had issued a cURL request, if you're familiar with cURL).

This is for security reasons.

So, how do you implement JSONP? It really depends on the server, but in general, your resource would look for a GET request that had a pre-determined querystring parameter (normally callback for simplicity):

http://192.168.5.100:8080/aggregators/datafile?callback=mycallback    

How do you make a JSONP call?

The server wraps the JSON in that callback, causing it to look something like the following:

mycallback({json:object});

This Stack Overflow answer goes into more detail.

The callback is the function the browser should hit when the request is executed, and that's what allows for cross-domain requests.

Now, on to CORS.

CORS is a system for allowing the browser to communicate with the server to determine whether or not it should accept a cross domain request. It's a bit complicated, but in general it involves settings up certain Headers on your API Server; and then executing an Ajax request in a particular fashion (for JQuery, use the withCredentials property for $.ajax). The server checks where the request is from, and if it's a valid source, it let's the browser know and the browser allows the request (I'm being simplistic).

MDN has a thorough explanation of CORS that is worth reading.

Community
  • 1
  • 1
George Stocker
  • 57,289
  • 29
  • 176
  • 237
  • sir, i have same problem but i am using jsonp. in chrome developer tool i can see the error is missing parameter, but i am supplying that. can you please give it a look http://stackoverflow.com/questions/23967360/jsonp-with-asmx-error-500 – Vikky Jun 02 '14 at 09:36