Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

166
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda