Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
Access the response of Node.JS Post Request

I'm trying the wrap my head around the Client Credentials Flow of Spotify API and in their documentation they have this way to get the Access Token:

var client_id = 'CLIENT_ID';
var client_secret = 'CLIENT_SECRET';

const authOptions = {
  url: "https://accounts.spotify.com/api/token",
  headers: {
    "Authorization":
      "Basic " +
      new Buffer.from(clientID + ":" + clientSecret).toString("base64"),
    "Content-Type": "application/x-www-form-urlencoded",
  },
  form: {
    grant_type: "client_credentials",
  },
  json: true,
};

request.post(authOptions, function(error, response, body) {
  if (!error && response.statusCode === 200) {
    var token = body.access_token;
  }
});

Now I'm trying to get that token and export or use it in the API calls but whatever I do, I cannot access that statement.

Putting the POST into a variable or function and calling it results in undefined.

This is what I'm trying to achieve:

import authOptions from "./credentials.js";
import pkg from "request";
const { post } = pkg;

const Spotify = {
  getAccessToken() {
    post(authOptions, function (error, response, body) {
      if (!error && response.statusCode === 200) {
        const token = body.access_token;
        return token;
      }
    });
  },

  async search(input) {
    const accessToken = Spotify.getAccessToken();
    const response = await fetch(
      `https://api.spotify.com/v1/search?q=${input}&type=artist`,
      {
        headers: {
          "Authorization": `Bearer ${accessToken}`,
          "Content-Type": "application/json",
        },
      }
    );
    const data = await response.json();
    console.log(data);
  },
};

export default Spotify;

Yet of course there's no Access Token returned from that post request.

Is there any way I can convert that piece of code into Async/Await?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can create a new promise:

async function getAccessToken(){
    return new Promise((resolve, reject) => {
        post(authOptions, function (error, response, body) {
            if(error){
                reject(error);
            } else if (response.statusCode === 200) {
                const token = body.access_token;
                resolve(token);
            }
         });
    });
};

The resolve/reject allows you to return that value when the callback is called, and it passes the error to the caller to handle. And you can use this format to promisify any callback-based function, by calling it inside of a promise and using resolve/reject to return the value.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda