【问题标题】:Using node-spotify-web-api to grant user access and fetch data使用 node-spotify-web-api 授予用户访问权限并获取数据
【发布时间】:2017-12-16 00:21:32
【问题描述】:

所以我是使用 OAuth 的新手,老实说,我在尝试完成这项工作时迷失了方向。我查找了Spotify's Authorization code 的文档,还找到了我使用的wrapper for node

我希望能够通过 spotify 登录用户,并从那里对 Spotify API 进行 API 调用。

通过一个示例,我最终得到了 /callback 路由的代码,该代码在用户被授予访问权限并且 Spotify Accounts 服务将您重定向到那里后被命中:

app.get('/callback', (req, res) => {
  const { code, state } = req.query;
  const storedState = req.cookies ? req.cookies[STATE_KEY] : null;

  if (state === null || state !== storedState) {
    res.redirect('/#/error/state mismatch');

  } else {
    res.clearCookie(STATE_KEY);

    spotifyApi.authorizationCodeGrant(code).then(data => {
      const { expires_in, access_token, refresh_token } = data.body;

      // Set the access token on the API object to use it in later calls
      spotifyApi.setAccessToken(access_token);
      spotifyApi.setRefreshToken(refresh_token);

      // use the access token to access the Spotify Web API
      spotifyApi.getMe().then(({ body }) => {
        console.log(body);
      });


      res.redirect(`/#/user/${access_token}/${refresh_token}`);
    }).catch(err => {
      res.redirect('/#/error/invalid token');
    });
  }
});

因此,在请求结束时,令牌被传递给浏览器以从那里发出请求:res.redirect('/#/user/${access_token}/${refresh_token}');

如果设置在那里重定向,我想将用户重定向到他可以搜索艺术家的表单。我是否需要以某种方式始终将令牌传递给参数?我将如何在那里重定向用户?我尝试简单地渲染一个新页面并在那里传递参数,但它不起作用。

【问题讨论】:

    标签: api express spotify


    【解决方案1】:

    您可以将令牌存储在各种位置,包括查询参数或 cookie - 但我建议使用 localstorage。当您的前端加载 /#/user/${access_token}/${refresh_token} 路由时,您可以获取这些值并将它们存储在本地存储中(例如 localstorage.set('accessToken', accessToken)),然后在需要调用 API 时检索它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 2019-06-22
      相关资源
      最近更新 更多