通过用户名从Spotify获取公共播放列表

Get public playlist from Spotify by username

本文关键字:获取 播放列表 Spotify 用户      更新时间:2023-09-26

我会尝试获取Spotify用户的公共播放列表,但我总是收到401错误。

{
    "error": {
        "status": 401,
        "message": "This request requires authentication."
    }
}

我使用此urlhttps://api.spotify.com/v1/users/id/playlists其中id必须是Spotify的用户名。我有一把oAuth密钥。我请求API使用这个JavaScript,JQuery代码:

$.ajax({
    url: "https://api.spotify.com/v1/users/" + $("#username").val() + "/playlists",
    Authorization: "Bearer my_OAuth_Token",
    Host: "api.spotify.com",
    Accept: "application/json",
    type: "GET",
    success: function (data){
        var count = data.items.length;
        for (var i = 0; i < aantal; i++) {
            $("#playlists").append('<option>' + data.items[i].name + '</option>');
        }
    },
    error: function (data) {
        $("#playlists").append("<option>error</option>");
    }
});

您需要将AuthorizationHost值作为标头发送,而不是作为选项对象的属性发送。还要注意,accepts应该是小写。试试这个:

$.ajax({
    url: "https://api.spotify.com/v1/users/" + $("#username").val() + "/playlists",
    headers: {
        Authorization: "Bearer my_OAuth_Token",
        Host: "api.spotify.com"
    },
    accepts: "application/json",
    type: "GET",
    success: function (data) {    
        var count = data.items.length;    
        for (var i = 0; i < aantal; i++) {
            $("#playlists").append('<option>' + data.items[i].name + '</option>');
        }
    },
    error: function (data) {
        $("#playlists").append("<option>error</option>");
    }
});

您可能也可以省略Host标头,因为我认为这不是必需的。