【问题标题】:Spotify API top-tracks brokenSpotify API 热门歌曲被打破
【发布时间】:2016-04-22 14:59:59
【问题描述】:

我正在尝试从艺术家那里获取第一个顶级曲目预览网址,但每次我进行搜索时,它都会返回一个损坏的 json。我可以将其解析为字符串以获得所需的内容,但 json 会容易得多。这是我的代码:

const https = require('https');
var open = require('open')

function songError(){
    console.log('There was some kind of error fetching your artist ;(');
}

function getTopSong(p_id){
    https.get('https://api.spotify.com/v1/artists/'+p_id+'/top-tracks?country=BR', function(res){
        res.on("data", function(chunk){
            var json = JSON.parse(chunk.toString('utf8'));
            console.log(json);
        });
    });
}

function getArtistID(p_name) {
    https.get('https://api.spotify.com/v1/search?q='+encodeURI(p_name)+'&type=artist', function(res){
        res.on("data", function(chunk) {
            var json = JSON.parse(chunk.toString('utf8'));
            if(json['artists']['items'][0]['id'] != undefined || json['artists']['items'][0]['id'] != null){
                console.log('id: ',json['artists']['items'][0]['id']);
                getTopSong(json['artists']['items'][0]['id']);
            }else
            {
                songError();
            }
        });
    });
}

getArtistID("rage against the machine");

第 329 行似乎有错误:

undefined:329
  "available_markets" : [ "AR", "AU", "AT", "BE", "BO", "BR", "BG", "CA", "CL", "CO", "CR", "CY", "CZ", "DK", "DO", "DE", "EC", "EE", "SV", "FI", "FR", "GR", "

我的问题是,我做错了什么还是真的坏了? 谢谢!

【问题讨论】:

    标签: json node.js spotify


    【解决方案1】:

    至少我可以毫无问题地卷曲它:

    $ curl -s 'https://api.spotify.com/v1/artists/2d0hyoQ5ynDBnkvAbJKORj/top-tracks?country=BR' | python -mjson.tool | tail
                "id": "25CbtOzU8Pn17SAaXFjIR3",
                "name": "Take The Power Back - Remastered",
                "popularity": 58,
                "preview_url": "https://p.scdn.co/mp3-preview/b44e8f96a219871587d0559970ca5dce71c891f2",
                "track_number": 3,
                "type": "track",
                "uri": "spotify:track:25CbtOzU8Pn17SAaXFjIR3"
            }
        ]
    }
    

    我对nodejs不太了解,但是你不需要把所有的回调串联到res.on("data"吗?

    https://nodejs.org/api/http.html#http_http_request_options_callback

    https.get('https://api.spotify.com/v1/artists/' + p_id + '/top-tracks?country=BR', function(res) {
      var body = [];
      res.on("data", function(chunk) {
        body.push(chunk);
      });
      res.on("end", function() {
        var json = JSON.parse(Buffer.concat(body).toString("utf8"));
        console.log(json);
      });
    });
    

    如果响应很长并且 Spotify 的服务器决定将响应发送回分块传输编码,那么 nodejs http 模块也可能会拆分响应。

    【讨论】:

    • 就是这样,我忘了把它全部连接起来,愚蠢的错误!谢谢!
    • 我刚刚意识到它可能与来自服务器的分块传输编码无关。无论如何,该 api 可能会将主体分成块,因此您可以下载千兆字节,而无需将所有内容读入内存。
    猜你喜欢
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 2012-12-29
    • 2015-05-11
    • 2013-01-04
    • 1970-01-01
    • 2016-07-01
    相关资源
    最近更新 更多