【问题标题】:Spotify API 400 Error Only Valid Bearer Authentication SupportedSpotify API 400 错误仅支持有效承载身份验证
【发布时间】:2017-10-04 02:42:56
【问题描述】:

我正在尝试使用 spotify api 来获取我的顶级艺术家和歌曲的数据。我在这里遵循了授权代码示例https://github.com/spotify/web-api-auth-examples。授权有效,我可以登录并查看我的基本信息,现在我正在尝试让我的顶级艺术家获得 400 错误:“仅支持有效的不记名身份验证”。

这是我的代码

    app.get('/get_top_artists', function(req, res) {
  var authString = 'Basic' + new Buffer(client_id + ':' + client_secret).toString('base64')
  var authOptions = {
    url: 'https://api.spotify.com/v1/me/top/artists',
    headers: {
      'Authorization': authString
    }, function(res) {
      console.log(res)
    }
  };

  request.post(authOptions, function(error, response, body) {
    if (!error && response.statusCode === 200) {
      var get_top_artists = body.get_top_artists;
      res.send({
        'get_top_artists': get_top_artists
      });
    }
  });
})

编辑

    app.get('/get_top_artists', function(req, res) {
  console.log('top artists');

  var authOptions = {
      url: 'https://accounts.spotify.com/api/token',
      form: {
        redirect_uri: redirect_uri,
        grant_type: 'authorization_code'
      },
      headers: {
        'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
      },
      json: true
    };

  request.post(authOptions, function(error, response, body) {
    console.log('request')
    if (!error && response.statusCode === 200) {

        var access_token = body.access_token,
            refresh_token = body.refresh_token;
        var options = {
          url: 'https://api.spotify.com/v1/me/top/artists',
          headers: { 'Authorization': 'Bearer ' + access_token },
          json: true
        };

        // use the access token to access the Spotify Web API
        request.get(options, function(error, response, body) {
          console.log('request 2')
          console.log(body);
        });
     }
  });
})

【问题讨论】:

    标签: javascript node.js api authentication


    【解决方案1】:

    正如您在示例中看到的,您需要首先使用基本标头进行调用,然后获取您获得的响应,然后调用 API。看起来您正在尝试使用基本凭据调用 API,但这是行不通的。

    https://github.com/spotify/web-api-auth-examples/blob/master/authorization_code/app.js#L73-L102

    【讨论】:

    • 我刚刚添加了一些编辑过的代码,这更接近我必须做的吗?它没有达到第二个请求,我不知道为什么,网络选项卡显示请求暂停了一段时间,并最终抛出一个空响应的错误
    • 我想通了,在 nodejs 方面过于复杂了
    猜你喜欢
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2016-04-06
    • 1970-01-01
    • 2020-07-05
    • 2020-06-18
    相关资源
    最近更新 更多