【发布时间】:2016-01-16 03:53:04
【问题描述】:
我刚开始使用这段代码测试一个简单的 API:
$http.get('/api/products?limit=10').then(function (response) {
console.log(response.status);
});
我得到这个错误:
SyntaxError: Unexpected token { 在 Object.parse (本机) 在 fromJson (http://localhost:8000/bower_components/angular/angular.js:1271:14) 在 defaultHttpResponseTransform (http://localhost:8000/bower_components/angular/angular.js:9460:16) 在http://localhost:8000/bower_components/angular/angular.js:9551:12 在 forEach (http://localhost:8000/bower_components/angular/angular.js:340:20) 在 transformData (http://localhost:8000/bower_components/angular/angular.js:9550:3) 在 transformResponse (http://localhost:8000/bower_components/angular/angular.js:10319:21) 在 processQueue (http://localhost:8000/bower_components/angular/angular.js:14792:28) 在http://localhost:8000/bower_components/angular/angular.js:14808:27 在 Scope.$eval (http://localhost:8000/bower_components/angular/angular.js:16052:28)
顺便说一句,使用这个非角度代码,它可以正常工作:
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);
});
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));
我真的不知道是什么问题,也已经尝试过 $resource 并且没有工作。 你可以看到整个代码on my github,请帮助。
【问题讨论】:
-
错误是当
response.data被接收并通过fromJson()时,response.data有一个无效的{存在,这使得data不是一个有效的Json对象。您可以记录response并验证您是否传递了有效的 Json? -
我添加了 res.write('{');和 res.write('}');在 for 循环之前和之后的 api 中它工作了,但为什么它使用 xmlHttpRequest 而不是 angular $http ?好奇怪……
-
非角度可能会起作用,因为您没有解析响应,因此它不关心是否返回了有效的 json。
$http处理解析,这是解析 thaat 抛出错误。获取在非角度控制台中返回的内容并将其粘贴到 json 验证器中......很可能会失败
标签: angularjs json node.js http angular-http