使用spotify-web-api-node生成身份验证令牌

J_D*_*J_D 3 spotify node.js

我是使用nodejs的新手,我正在开发一个项目,我可以通过搜索一次添加一首歌来制作自定义播放列表.我已经能够获取代码来执行搜索并抓取正确的ID,但是当尝试添加到播放列表时,我收到有关范围错误的错误.长话短说,我做错了类型的身份验证.

所以我读了一下spotify-web-api-node文档,但是我在生成授权URL然后获得响应之间迷路了,然后由另一个方法使用它来获取授权令牌.我不确定是否有其他方法我没有看到它会发出请求,或者我是否应该通过普通节点方法进行常规请求.

我正在使用的代码几乎是来自以下链接的复制粘贴(https://github.com/thelinmichael/spotify-web-api-node#authorization),其中第二个框带有标题"以下用途一个硬编码的授权代码..​​...."是我丢失的地方......我需要从响应中获取代码,但我不确定我是如何发送请求来获取响应的,createAuthorizeURL方法似乎只是制作实际网址但不发送它.

Mic*_*lin 7

我认为混淆源于授权代码流的工作方式,以及我为节点包装器编写文档的方式.createAuthorizeURL方法的目的是帮助您创建转发用户所需的URL.

从您链接到的同一文档:

In order to get permissions, you need to direct the user to our Accounts service. 
Generate the URL by using the wrapper's authorization URL method.
Run Code Online (Sandbox Code Playgroud)

因此,假设用户首先进入您的网站http://www.jd.example.com.它将有一个Spotify样式按钮,表示在此处登录.该按钮链接到createAuthorizeURL生成的URL.URL的一个非常重要的部分是redirect_uri查询参数.例如,您将生成的URL看起来像

https://accounts.spotify.com:443/authorize?client_id=5fe01282e44241328a84e7c5cc169165&
response_type=code&redirect_uri=https://www.jd.example.com/callback&
scope=playlist-modify-public
Run Code Online (Sandbox Code Playgroud)

当用户单击该按钮时,他们将通过Spotify网站上的身份验证和授权流程(accounts.spotify.com/).但是,当他们完成此流程时,他们将被Spotify指向您在createAuthorizeURL中提供的相同redirect_uri,例如https://www.jd.example.com/callback.

这意味着您的Web服务器(例如Express)需要能够处理对redirect_uri的请求.如果您的Web服务器确实是Express,它可能看起来像这样.

/* Some express.js setup here */
/* Some spotify-web-api-node setup here */

/* Handle authorization callback from Spotify */
app.get('/callback', function(req, res) {

  /* Read query parameters */
  var code  = req.query.code; // Read the authorization code from the query parameters
  var state = req.query.state; // (Optional) Read the state from the query parameter

  /* Get the access token! */
  spotifyApi.authorizationCodeGrant(code)
    .then(function(data) {
      console.log('The token expires in ' + data['expires_in']);
      console.log('The access token is ' + data['access_token']);
      console.log('The refresh token is ' + data['refresh_token']);

      /* Ok. We've got the access token!
         Save the access token for this user somewhere so that you can use it again.
         Cookie? Local storage?
      */

      /* Redirecting back to the main page! :-) */
      res.redirect('/');

    }, function(err) {
      res.status(err.code);
      res.send(err.message);
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!