Я получаю ошибку 401 в Spotify API, я думаю, это из-за того, как я устанавливаю токен доступа, может кто-нибудь посоветовать? - PullRequest
0 голосов
/ 11 июля 2020

Я новичок в программировании и пытаюсь использовать API spotify, чтобы иметь возможность получать поисковые треки на spotify

Я получаю несанкционированный ответ 401, и я почти уверен, что это что-то связано с моим токеном доступа и с тем, как я его запрашиваю.

Я пытаюсь следовать руководству по авторизации Spotify и успешно получаю журнал, и токен доступа отображается в URL-адресе.

Кто-нибудь знает, почему я не могу получить плейлисты.

Это мой код: Приложение. js

request.post(authOptions, function(error, response, body) {
  if (!error && response.statusCode === 200) {

    var access_token = body.access_token,
        refresh_token = body.refresh_token;

    var options = {
      url: 'https://api.spotify.com/v1/me',
      headers: { 'Authorization': 'Bearer ' + access_token },
      json: true
      };

    // use the access token to access the Spotify Web API
    request.get(options, function(error, response, body) {
      console.log(body);
    });

    // we can also pass the token to the browser to make requests from there
    res.redirect('/#' +
      querystring.stringify({
        access_token: access_token,
        refresh_token: refresh_token
      }));
   } else {
    res.redirect('/#' +
      querystring.stringify({
        error: 'invalid_token'
      }));
   }
  });
 }
});

app.get('/refresh_token', function(req, res) {

// requesting access token from refresh token
var refresh_token = req.query.refresh_token;
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + 
client_secret).toString('base64')) },
 form: {
  grant_type: 'refresh_token',
  refresh_token: refresh_token
},
json: true
};

 request.post(authOptions, function(error, response, body) {

if (!error && response.statusCode === 200) {
  var access_token = body.access_token;
  res.send({
    'access_token': access_token
   });
 }
});

request.post(Post, function(req, res, body) {
var access_token = body.access_token,
    refresh_token = body.refresh_token;
var post = {
url: 'https://accounts.spotify.com/api/token',
form: {
  code: code,
  redirect_uri: redirect_uri,
  grant_type: 'authorization_code'
},
headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + 
client_secret).toString('base64')) }
}
});

});

getPlaylists. js

var spotifyApi = new SpotifyWebApi();

var client_id = process.env.CLIENT_; // Your client id

var client_secret = process.env.CLIENT_S; // Your secret

var redirect_uri = 'http://localhost:8888/playlists';


 spotifyApi.setAccessToken('access token');

 spotifyApi.searchTracks('Love')
 .then(function(data) {
  console.log('Search by "Love"', data.body);
 }, function(err) {
 console.error(err);
 });

Я устанавливаю токен доступа в getPlaylists. js file

Любая помощь будет очень приветствоваться.

Как бы вы передали токен доступа?

Заранее благодарим за любую помощь, очень признательны.

...