SpotifyWebApi - nodeJS

时间:2018-04-09 13:05:39

标签: javascript node.js spotify

我尝试使用spotify API开发一个简单的应用程序,但我无法使用身份验证。在前端,我有一个按钮,发送一个/ authorize调用,如下所示:

var CLIENT_ID = 'blabla'; // Your client id
var CLIENT_SECRET = 'blablabla'; // Your secret
var REDIRECT_URI = 'http://localhost:4001/logincallback';
const STATE_KEY = "spotify_auth_state";
const scopes = ['user-read-private', 'user-read-email'];

const spotifyApi = new Spotify({
  clientId: CLIENT_ID,
  clientSecret: CLIENT_SECRET,
  redirectUri: REDIRECT_URI
});

/**
 * The /login endpoint
 * Redirect the client to the spotify authorize url, but first set that user's
 * state in the cookie.
 */
const generateRandomString = N => (Math.random().toString(36)+Array(N).join('0')).slice(2, N+2);

router.get('/', (_, res) => {
  const state = generateRandomString(16);
  res.cookie(STATE_KEY, state);
  var authorized_url = spotifyApi.createAuthorizeURL(scopes, state);
  res.redirect(authorized_url);
});

module.exports = router;

然后在/ logincallback中我有

var CLIENT_ID = 'blabla'; // Your client id
var CLIENT_SECRET = 'blabla'; // Your secret


router.get('/', (req, res) => {
  const { code, state } = req.query;
  const storedState = req.cookies ? req.cookies[STATE_KEY] : null;
  // first do state validation
  if (state === null || state !== storedState) {
    res.redirect('/#/error/state mismatch');
    console.log("Incorrect state");
  // if the state is valid, get the authorization code and pass it on to the client
  } else {
    res.clearCookie(STATE_KEY);
    // Retrieve an access token and a refresh token
    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);
      });

      // we can also pass the token to the browser to make requests from there
      res.redirect(`/#/user/${access_token}/${refresh_token}`);
    }).catch(err => {
      console.log(err);
      res.redirect('/#/error/invalid token');
    });
  }
});

这些都是直接从Spotify API示例中复制的。但是,对res.redirect(authorized_url)的调用似乎没有 - 例如,我收到/授权请求但没有后续请求/ logincallback。如果我执行res.redirect(' / logincallback'),则API会以错误请求进行响应。我使用Postman将没有任何参数的请求直接发送到/ logincallback,但这显然失败了,因为它错过了第一次调用spotify API时提供的信息。邮递员/授权请求给了我一个我在开发人员仪表板中将这些路由添加到白名单的信息:

https://localhost:4001/logincallback/ 
http://localhost:4001/logincallback/ 
https://localhost:4001/logincallback
http://localhost:4001/logincallback 
https://localhost:4001/

简短版本:使用spotifyApi.createAuthorizeURL调用API来识别API

1 个答案:

答案 0 :(得分:0)

在Spotify上将fflush(NULL)注册为回调API无效,因为Spotify服务器不知道将请求路由到何处。 我使用它的方法是将我的应用程序部署在heroku上(即获取公共端点),然后注册该回调程序。