Tell me, where is the dog buried?

There is such an example of calling $ http.get on Angular.
HTML:

<body ng-app="httptest"> <div ng-controller="getjson"> <pre> <div>{{data}}</div> </pre> </div> </body> 

Js

 var app = angular.module("httptest", []); app.controller("getjson", ["$scope", "$http", function($scope, $http) { $http.get("http://codepen.io/anon/pen/LVEwdw.js"). success(function(res) { $scope.data = res; }); }]); 

( http://codepen.io/stoxa/pen/pyORVj?editors=1111 )

with the link http://codepen.io/anon/pen/LVEwdw.js ,

returning jsoninu -

 [{"nama":"Maria Belen","alamat":"Spanyol","pictures":["small.png","medium.png","big.png"]},{"nama":"Betty La Fea","alamat":"Spanyol","pictures":["small.png","medium.png","big.png"]}] - Работает 

with the link http://www.mocky.io/v2/571e719c0f00008e1b127cce , returning the same jsonin - does not work ..

I tried and inserted content-type into headers. The result is the same(

  • See the error in the browser console - Grundy
  • I look at the kodpen console, no errors - stoxa
  • too many links in question, and too little code. Paste the code that you use and that doesn't work directly into the question - Grundy
  • Just in case, returning json as an array is sometimes unsafe (it becomes a valid js code, unlike json representing an object {}) - Vladimir Gamalyan

3 answers 3

I tried your code, it crashed to the console:

 XMLHttpRequest cannot load http://www.mocky.io/v2/571e719c0f00008e1b127cce. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. 

It looks like a problem with the cross-domain.

The headers in response to the preflight options from mocky.io:

 HTTP/1.1 200 OK Server: Cowboy Connection: close Content-Type: application/json; charset=utf-8 Date: Tue, 26 Apr 2016 08:05:56 GMT Via: 1.1 vegur 

There is no required Access-Control-Allow-Origin header. Accordingly, the browser suppresses further data acquisition.

If you really need to work with mocky.io, try JSONP, which is also offered there. There are no cross-domain restrictions for it.

    The code works - but for some reason mocky.io returns an empty response. Learn to use developer tools in your browser.

    • Yes, this is the question - why not return? I look in the direction of headers, charsets. But I didn’t manage to get the data back with various combinations of configs in the header - stoxa
     var app = angular.module("httptest", []); app.controller("getjson", ["$scope", "$http", function($scope, $http) { var url = "http://www.mocky.io/v2/571e719c0f00008e1b127cce" + "?callback=JSON_CALLBACK"; $http({ contentType: "application/json; charset=utf-8",method: 'jsonp',url:url,headers: {'Content-Type': 'application/x-www-form-urlencoded'}}) .success(function(data) { if (data) { $scope.data = data; } }); }]);