Spotify授权代码授予:错误的请求

时间:2018-07-05 22:17:42

标签: javascript node.js express spotify bad-request

我正在尝试创建一个使用Spotify API的网站,而我一直试图使授权代码流程正常工作。下面是我正在使用的代码。

app.get('/login', function(req, res) {
  var scope = 'user-read-private';
  res.redirect('https://accounts.spotify.com/authorize?' +
    querystring.stringify({
      response_type: 'code',
      client_id: clientId,
      scope: scope,
      redirect_uri: redirectUri,
      state: state
    }));
});

app.get('/callback', function(req, res) {
  res.status(200);
  var code = req.query.code;
  console.log('\ncode:', code, '\n');
  spotify.authorizationCodeGrant(code).then(
    function(data) {
      console.log('The access token expires in ' + data.body['expires_in']);
      console.log('The access token is ' + data.body['access_token']);

      spotify.setAccessToken(data.body['access_token']);
      spotify.setRefreshToken(data.body['refresh_token']);
    },
    function(err) {
      console.log('Could not login!', err);
    }
  );
  res.redirect('/');
});

我遇到的问题是,当它进入authorizeCodeGrant调用时,它只是失败,并给我一个400错误的请求错误,我不确定为什么,因为我知道我是从Spotify获取代码的,似乎不起作用。

var path = require('path');
var express = require('express');
var request = require('request');
var exphbs = require('express-handlebars');
var querystring = require('querystring');
var url = require('url');
var Spotify = require('spotify-web-api-node');
var keys = require('./keys');

var scopes = ['playlist-modify-private', 'user-read-private'],
  redirectUri = 'http://localhost:3000/callback',
  clientId = 'client_id',
  clientSecret = 'client_secret',
  state = 'some-state-of-my-choice';

var spotify = new Spotify({
  redirectUri: redirectUri,
  clientId: clientId,
  redirectUri: redirectUri
});

var results = [];
var login = 1;//keeps track if logged into spotify

var tokenExpiration;

var app = express();
var port = process.env.PORT || 3000;

app.engine('handlebars', exphbs({ defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

app.get('/', function(req, res, next){
   res.status(200);
   res.render('searchPage', {
     login: login,
     results: results
   });
});

app.get('/login', function(req, res) {
  var scope = 'user-read-private';
  res.redirect('https://accounts.spotify.com/authorize?' +
    querystring.stringify({
      response_type: 'code',
      client_id: clientId,
      scope: scope,
      redirect_uri: redirectUri,
      state: state
    }));
});

app.get('/callback', function(req, res) {
  var code = req.query.code;
  console.log('\ncode:', code, '\n');
   spotify.authorizationCodeGrant(code).then(
     function(data) {
       console.log('The access token expires in ' + data.body['expires_in']);
       console.log('The access token is ' + data.body['access_token']);

       spotify.setAccessToken(data.body['access_token']);
       spotify.setRefreshToken(data.body['refresh_token']);

       tokenExpiration = new Data().getTime()/1000 + data.body['expires_in'];
       login = 0;
     },
     function(err) {
       console.log('Could not login!', err);
     }
   );
  if(login == 0){
    res.redirect('/#' +
    querystring.stringify({
      access_token: spotify.getAccessToken(),
      refresh_token: spotify.getRefreshToken()
    }));
  }else{
    res.redirect('/');
  }
});

var numberOfTimesUpdated = 0;

setInterval(function() {
  if(++numberOfTimesUpdated > 5 && login == 0) {
    clearInterval(this);

    spotify.refreshAccessToken().then(
      function(data) {
        tokenExpiration = new Data().getTime()/1000 + data.body['expires_in'];
        spotify.setAccessToken(data.body['access_token']);
      },
      function(err) {
        console.log('Could not refresh the token!', err.message);
      }
    );
  }
}, 1000);

app.post('/search/:title', function(req, res) {
  var search = req.params.title.toLowerCase();//req.body.search;
  console.log('search', search);

  resutls = [];

  spotify.searchTracks(search, function(err, data) {
    if(err) {
      console.error('something went wrong...');
      return;
    }

    console.log('I got' + search.body.tracks.total + 'results!');

    search.body.tracks.items.forEach(function(track){
      results.push({
        artist: track.artist[0].name,
        song: track.name,
        preview: track.external_urls.sp,
        album: track.album.name
      });
      res.render('searchPage', {
        login: login,
        results: results
      });
    });
  });
});

app.use(express.static('public'));

app.listen(port, function(err){
  console.log("== Server is listening on port", port);
});

上面是服务器的完整代码。

0 个答案:

没有答案
相关问题