【发布时间】:2015-09-28 17:14:28
【问题描述】:
我最近在浏览器中使用 ajax 一直在使用 spotify api,到目前为止我还没有遇到任何问题。但是现在我尝试将它与 node.js 一起使用,我只是在做一个简单的获取并尝试将字符串解析为 JSON 对象,但我得到一个语法错误作为回报。代码如下:
var https = require('https')
var dir = "https://api.spotify.com/v1/search?query=tania+bowra&offset=0&limit=20&type=artist"
https.get(dir, function (response){
response.setEncoding('utf8');
response.on('data', function (data){
var str = data;
var jObj = JSON.parse(str);
console.log(jObj);
})
})
这是我收到的响应并希望将其解析为 Json 对象:
{
"artists": {
"href": "https://api.spotify.com/v1/search?query=tania+bowra&offset=0&limit=20&type=artist",
"items": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/08td7MxkoHQkXnWAYD8d6Q"
},
"followers": {
"href": null,
"total": 21
},
"genres": [],
"href": "https://api.spotify.com/v1/artists/08td7MxkoHQkXnWAYD8d6Q",
"id": "08td7MxkoHQkXnWAYD8d6Q",
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/f2798ddab0c7b76dc2d270b65c4f67ddef7f6718",
"width": 640
},
{
"height": 300,
"url": "https://i.scdn.co/image/b414091165ea0f4172089c2fc67bb35aa37cfc55",
"width": 300
},
{
"height": 64,
"url": "https://i.scdn.co/image/8522fc78be4bf4e83fea8e67bb742e7d3dfe21b4",
"width": 64
}
],
"name": "Tania Bowra",
"popularity": 4,
"type": "artist",
"uri": "spotify:artist:08td7MxkoHQkXnWAYD8d6Q"
}
],
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total": 1
}
}
这是我得到的错误:
undefined:16
SyntaxError: Unexpected end of input
at Object.parse (native)
at IncomingMessage.<anonymous> (C:\path:12:19)
at IncomingMessage.emit (events.js:107:17)
at IncomingMessage.Readable.read (_stream_readable.js:373:10)
at flow (_stream_readable.js:750:26)
at resume_ (_stream_readable.js:730:3)
at _stream_readable.js:717:7
at process._tickCallback (node.js:355:11)
浏览器中的相同请求可以完美运行,并且在我签入http://jsonlint.com/ 时,显然 Json 格式没有错误
【问题讨论】:
-
您解析字符串的时间过早。您应该在将所有数据块聚合为单个字符串后进行解析。随着数据块的接收,数据回调会被执行多次。
标签: javascript node.js api spotify