aroe
aroe

Reputation: 161

can't seem to access value outside of function, nodejs

I am looking to get back the value "bearerToken" from the function "accesstokenAuth()". My issue is I'm not sure how to get that value out of a function even when I return/resolve it. Here is my code:

const SpotifyWebApi = require('spotify-web-api-node');
const http = require("http");
const request = require('request');
const querystring = require('querystring');
const { post } = require('request');
const express = require('express');
const { response } = require('express');
const https = require('follow-redirects').https;


//sets express server vars
const app = express()
const port = 8080

app.get('/', (req, res) => {
  res.send('Server Connected')
})

app.listen(port, () => {
  console.log(`Now serving on ${port} at ${process.env.URI} `)
})


require('dotenv').config();


//authenticate to SpotifyAPI
var spotifyApi = new SpotifyWebApi({
  clientId: process.env.CLIENT_ID,
  clientSecret: process.env.SECRET_ID,
  redirectUri: process.env.URI,
});

const scope = 'user-read-private user-read-email ';
const authUrl = 'https://accounts.spotify.com/api/token?grant_type=client_credentials';

//Headers needed to auth to SpotifyAPI for Bearer token
const tokenHeaders = {
  'Authorization': process.env.ACCESSTOKEN,
  'Content-Type': 'application/x-www-form-urlencoded',

};


//spotify Auth Payload
const options = {
  'method': 'POST',
  'url': authUrl,
  'headers': tokenHeaders
};

//does the function that calls this function need to be async??
const accessToken = async function accessTokenAuth() {
  return new Promise((resolve) => {
     request(options, (error, response) => {
        if (error) throw new Error(error);
        const accessTokenBody = response.body;
        const obj = JSON.parse(accessTokenBody);
        const bearerToken = ("Bearer " + obj.access_token);
        resolve(bearerToken)
     });
  })
}

let bearer = bearerToken;
console.log(bearer)



//Add first playlists request using the bearer token



const playlistUrl = 'https://api.spotify.com/v1/me/playlists'

const playlistHeaders = {
  'Authorization': bearer,
  'Content-Type': 'application/x-www-form-urlencoded'
}

const playlistAuth = {
  'method':'GET',
  'url': playlistUrl,
  'headers': playlistHeaders

}




function getUserPlaylists() {
  request( playlistAuth, (error, response) => {
    if (error) throw new Error(error);
    const userPlaylistData = response.body;
    console.log(userPlaylistData)

  });
}

getUserPlaylists() 

As you can see I need to take the "bearerToken" value and then present it to the function below that called "getUserPlaylist" so I can get further data after authenticating. Thank you!

Upvotes: 0

Views: 127

Answers (1)

Brandon
Brandon

Reputation: 1617

The variable bearerToken is out of scope since it is scoped within your function.

if you return resolve(bearerToken) within your function then accessToken should equal your bearerToken.

Side note, you can rewrite your function like so.

I could be wrong but I don't think that you need the promise.

const accessToken = () => request(options, (error, response) => {
  console.log({options, response});
  if (error) throw new Error(error);
  
  const accessTokenBody = response.body;
  const obj = JSON.parse(accessTokenBody);
  const bearerToken = ("Bearer " + obj.access_token);
  return bearerToken;
});

Upvotes: 1

Related Questions