簡體   English   中英

角度$ http.get錯誤,意外令牌

[英]angular $http.get error, unexpected token

我剛剛開始使用以下代碼測試簡單的API:

$http.get('/api/products?limit=10').then(function (response) {
    console.log(response.status);
});

我得到這個錯誤:

SyntaxError:意外的令牌{在fromJson( http:// localhost:8000 / bower_components / angular / angular.js:1271:14 )的Object.parse(本機)處,默認為HTTPHttpResponseTransform( http:// localhost:8000 / bower_components / angular /在forEach( http:// localhost:8000 / bower_components / angular / angular.js:340:20處的http:// localhost:8000 / bower_components / angular / angular.js:9551:12處的angular.js:9460:16 ) )在transformQueue( http:// localhost:8000 / bower_components / angular / angular.js:9550:3 )在processResponsehttp:// localhost:8000 / bower_components / angular / angular.js:10319:21 )在processQueue(在Scope。$ eval( http://上的http:// localhost:8000 / bower_components / angular / angular.js:14808:27處的http:// localhost:8000 / bower_components / angular / angular.js:14792:28本地主機: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並且沒有用。 您可以在我的github上看到整個代碼,請幫忙。

我是這樣在客戶端解決的:

var WareHouseResource = $resource('/api/products?limit=10', {}, {
        query: {
            method: 'GET',
            isArray: true,
            transformResponse: function(data) {
                data = ('[' + data + ']').replace(/}/g, '},').replace(',\n]', ']');
                return angular.fromJson(data);
            }
        }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM