Home > other >  Access the response of Node.JS Post Request
Access the response of Node.JS Post Request

Time:12-08

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?

CodePudding user response:

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.

  • Related