Megan
Megan

Reputation: 1

Trouble with Spotify WebAPI

I'm having trouble running this in my html. It works when I run it in my node.js command prompt. I think it's because require() only works in node.js and doesn't work with the clientside of html. Is there a way I can change this to work in my html?

My authorization code is run with it, as well as my user_id in the code.

var request = require("request");
var user_id = "";
var accessToken= "Bearer";

var playlists_url = "https://api.spotify.com/v1/users/"+user_id+"/playlists";

request({url: playlists_url, headers:{ "Authorization": accessToken}},
function(err, res){
  if (res){
    var playlists= JSON.parse(res.body);
    // console.log(JSON.stringify(playlists.items, null, ""));
    var playlist_url = playlists.items[0].href;
    request({url: playlist_url, headers:{ "Authorization": accessToken}},
    function(err, res){
      if (res){
        var playlist = JSON.parse(res.body);
        console.log("playlist:" + playlist.name);
        playlist.tracks.items.forEach(function(track){
          console.log(track.track.name);
        });
      }
  })
 }
})

Upvotes: 0

Views: 68

Answers (2)

Laudinio
Laudinio

Reputation: 33

You can use Spotify Web API JS and then jest write:

var Spotify = require('spotify-web-api-js');
var spotifyApi = new Spotify();

spotifyApi.getUserPlaylists(your_user_id)
   .then(function(data) {
       console.log('User playlists', data);
   }, function(err) {
       console.error(err);
   });

Upvotes: 1

0xA03DA
0xA03DA

Reputation: 13

You can use jQuery.get() for a request from the client:

var user_id = '';
var accessToken= 'Bearer';
var requestUrl = 'https://api.spotify.com/v1/users/' + user_id + '/playlists';

$.get(requestUrl, { 'authorization': accessToken; }, function(data) {
    // process the received data...
});

Upvotes: 0

Related Questions