【问题标题】:spotify-web-api-node 401 unauthorized errspotify-web-api-node 401 未经授权的错误
【发布时间】:2020-09-06 23:58:11
【问题描述】:

我正在尝试基于 nodejs 'spotify-web-api-node' 的代码做一个简单的示例: https://github.com/thelinmichael/spotify-web-api-node,我试图让示例正常工作,而无需提示用户登录。

我已经设置了一个 spotify 开发者应用,所以我可以获得一个 clientId 和 clientSecret,我添加了我的本地主机的 url:

我的函数在按下按钮时被调用,并尝试验证帐户,然后搜索 elvis 的相册。我在上面的设置中添加了相同的url作为redirectUri:

//popularify spotify api route
app.post('/popularifyRequest', async function (req, res) {
  console.log("/popularifyRequest req.body=",req.body)
  
  var SpotifyWebApi = require('spotify-web-api-node');
 
  // credentials are optional
  var spotifyApi = new SpotifyWebApi({
    clientId: 'f8```````````````````',
    clientSecret: 'b7``````````````````````',
    redirectUri: 'http://localhost:8080/popularify'
  });
 
  // Get Elvis' albums
  spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE').then(
    function(data) {
      res.send(data.body);
    },
    function(err) {
      res.send(err);
    }
  );

});

但是当函数被调用时;我收到 401 错误:

name: "WebapiError", message: "Unauthorized", statusCode: 401}

我的帐户验证有误吗?

【问题讨论】:

    标签: node.js npm spotify


    【解决方案1】:

    从 Spotify 获得授权(重定向到 Shopify 并重定向回 /popularify)后,您应该使用返回的令牌

    // in app.get("/popularify", async function (req, res))
    
    spotifyApi.authorizationCodeGrant(code).then(
      function(data) {
    
    
        spotifyApi.setAccessToken(data.body['access_token']);
        spotifyApi.setRefreshToken(data.body['refresh_token']);
    
    spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE').then(
            function(data) {
              res.send(data.body);
            },
            function(err) {
              res.send(err);
            }
          );
    
    
    
      }).catch((err) {
        console.log('Something went wrong!', err);
      })
    );
    

    【讨论】:

    • 我了解此工作流程并且能够使其正常工作,但是有什么方法可以在不让用户登录的情况下运行查询?我构建了一个有效的 /authorize url 并返回了一个代码,我尝试在您发布的 setAccessToken('32234234234') 行中使用该代码,但仍然无法验证查询
    • 不要像这样使用您的代码:spotifyApi.authorizationCodeGrant(code) 获取访问令牌和刷新令牌并像这样使用 em:spotifyApi.setAccessToken(data.body['access_token']);spotifyApi.setRefreshToken(data.body['refresh_token']);
    猜你喜欢
    • 2017-11-09
    • 1970-01-01
    • 2017-10-07
    • 2019-02-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 2019-05-06
    相关资源
    最近更新 更多