【问题标题】:Getting a Spotify access token using only client credentials (Spotify Web API Node)仅使用客户端凭据获取 Spotify 访问令牌(Spotify Web API 节点)
【发布时间】:2018-03-29 03:22:12
【问题描述】:

我正在尝试使用 Node.js 和 Spotify Web API NodeClient Credential flow 获取 Spotify 访问令牌(仅包含客户端 ID 和客户端密码)。这是我的代码:

var SpotifyWebApi = require('spotify-web-api-node');

var spotifyApi = new SpotifyWebApi({
  clientId : clientId, // my Client ID
  clientSecret : clientSecret // my Client Secret
});

spotifyApi.clientCredentialsGrant()
  .then(function(data) {
    spotifyApi.setAccessToken(data.body['access_token']);
  }, function(err) {
    console.log('Something went wrong when retrieving an access token', err);
  });

我遇到的问题是我总是收到以下错误:

TypeError: spotifyApi.clientCredentialsGrant is not a function

我可以毫无问题地访问这个库中的许多其他功能。例如,我可以这样写:

console.log(`The Client secret is ${spotifyApi.getClientSecret()}`);
console.log(`The Client ID is ${spotifyApi.getClientId()}`);

我在控制台中得到了预期的输出:

The Client secret is [my Client Secret]
The Client ID is [my Client ID]

有趣的是,通过使用 WebStorm 的代码完成,我可以看到许多其他可用的方法。事实上,我可以看到总共 88 种方法(甚至比列出的 here 还要多),但该列表中也缺少 clientCredentialsGrant()

我认为这会相当简单,但我一定在某个地方犯了一个简单的错误。有没有人成功使用过这个方法?或者以前有人遇到过这个错误吗?我应该这样做有更好的方法吗?

【问题讨论】:

    标签: node.js spotify


    【解决方案1】:

    出于安全原因,您必须在服务器端使用此授权流程。 显然,这是为了避免您在每个人都可以阅读代码的应用程序上使用您的秘密令牌。 看看这个:https://github.com/thelinmichael/spotify-web-api-node#authorization

    【讨论】:

      【解决方案2】:

      该问题的快速解决方法是将其包装在 if 语句中,同时检查 spotifyApi 和 clientCredentialsGrant 函数:

      var SpotifyWebApi = require('spotify-web-api-node');
      var spotifyApi = new SpotifyWebApi({
        clientId : clientId, // my Client ID
        clientSecret : clientSecret // my Client Secret
      });
      
      // insert this line
      if (spotifyApi & spotifyApi.clientCredentialsGrant) {
      spotifyApi.clientCredentialsGrant()
        .then(function(data) {
          spotifyApi.setAccessToken(data.body['access_token']);
        }, function(err) {
          console.log('Something went wrong when retrieving an access token', err);
        });
      }

      可能是一个 hack,但它对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-08
        • 2015-08-28
        • 2018-12-14
        • 2020-10-09
        • 2017-02-14
        • 1970-01-01
        • 2016-01-06
        • 2018-01-08
        相关资源
        最近更新 更多