我想从函数“ accesstokenAuth()”中取回值“ bearerToken”。我的问题是,即使我返回/解析它,我也不知道如何从函数中获取该值。这是我的代码:
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()
如您所见,我需要获取“ bearerToken”值,然后将其提供给名为“ getUserPlaylist”的函数,以便在进行身份验证后获得更多数据。谢谢!
答案 0 :(得分:1)
变量bearerToken
超出了范围,因为它的范围在您的函数之内。
如果您在功能内return resolve(bearerToken)
,则accessToken
应该等于您的bearerToken
。
旁注,您可以像这样重写函数。
我可能错了,但我不认为你需要诺言。
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;
});