I've been using spotify api lately using ajax in browser and I haven't got any problem so far. But now I'm trying to use it with node.js, I'm just doing a simple get and trying to parse the string into JSON object but i get a syntax error in return. Here is the code:
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);
})
})
This is what I receive as response and want to parse it into Json object:
{
"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
}
}
And this is the error i get:
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)
The same petition in browser works perfectly and there is no error aparently in Json format as I checked in http://jsonlint.com/
The 'data' callback function will be called with each chunk of data received so you have to collect all the data and then parse it:
https.get(dir, function (response){
var str = '';
response.setEncoding('utf8');
response.on('data', function (data){
str += data;
});
response.on('end', function (){
var jObj = JSON.parse(str);
console.log(jObj);
});
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.