I was just starting to test a simple API using this code:
$http.get('/api/products?limit=10').then(function (response) {
console.log(response.status);
});
And I get this error:
SyntaxError: Unexpected token { at Object.parse (native) at fromJson (http://localhost:8000/bower_components/angular/angular.js:1271:14) at defaultHttpResponseTransform (http://localhost:8000/bower_components/angular/angular.js:9460:16) at http://localhost:8000/bower_components/angular/angular.js:9551:12 at forEach (http://localhost:8000/bower_components/angular/angular.js:340:20) at transformData (http://localhost:8000/bower_components/angular/angular.js:9550:3) at transformResponse (http://localhost:8000/bower_components/angular/angular.js:10319:21) at processQueue (http://localhost:8000/bower_components/angular/angular.js:14792:28) at http://localhost:8000/bower_components/angular/angular.js:14808:27 at Scope.$eval (http://localhost:8000/bower_components/angular/angular.js:16052:28)
Btw, with this non angular code, it works fine:
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
httpGetAsync('/api/products?limit=10', function(response) {
console.log(response);
});
Some code of the API:
res.writeHead(200, {
'Content-Type': 'application/x-json-stream'
});
// random delay
setTimeout(function () {
var i;
for (i=0; i<limit; i+=1) {
res.write(JSON.stringify(createRandomItem(i+skip, sort)) + '\n');
}
res.end();
}, 100 + Math.floor(Math.random() * 3000));
I really can't figure out what's the problem, also already tried $resource and didn't worked. You can see the whole code on my github, please help.
response.datais received and passed throughfromJson(), theresponse.datahas an invalid{present that makes thedatanot a valid Json object. Can you log theresponseand verify that you are passing valid Json?$httphandles the parsing and it's the parsing thaat is throwing error. Take what was returned in non angular console and paste it into a json validator...most likely it fails