0

I am using the Spotify API and need to get an access token, although the example/guide (https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow) is written in cURL, which I need to translate to Javascript.

The main issue is setting the request body parameter "grant_type" to "client_credentials" and "The body of this POST request must contain the following parameters encoded in application/x-www-form-urlencoded as defined in the OAuth 2.0 specification:" which I'm not sure how to do.

I've tried the cURL on a command prompt and it works fine, but I will not be using cURL.

What I'm trying to do

curl -X "POST" -H "Authorization: Basic ZjM4ZjAw...WY0MzE=" -d grant_type=client_credentials https://accounts.spotify.com/api/token

What I have

var auth_id = "";

var getToken = new XMLHttpRequest();

getToken.open('POST', 'https://accounts.spotify.com/api/token', true);
getToken.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
getToken.setRequestHeader('grant_type', 'client_credentials'); //this param needs to be in body but how???
getToken.setRequestHeader('Authorization', 'Basic (this part is my client id but I am not including it for obvious reasons)');

getToken.onload = function (){
    var data = JSON.parse(this.response);
    console.log(data);
    auth_id=data.access_token;
}
getToken.send("client_credentials");
Eli.helpmepls
  • 11
  • 1
  • 4
  • As I understand you need to send JSON to the API. Check [this question](https://stackoverflow.com/questions/39519246/make-xmlhttprequest-post-using-json) – Cray May 07 '19 at 04:32

1 Answers1

0

I would recommend you to use a more modern fetch api like native fetch https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API or a third party library like axios https://github.com/axios/axios

Using fetch it is fairly easy

const url = 'https://accounts.spotify.com/api/token';
const request = new Request(url, {
  headers: new Headers({
    Authorization: 'Basic XXX',
  }),
  body: JSON.stringify({
    grant_type: 'client_credentials'
  }),
  method: 'POST',
);

const response = await fetch(request);
marcobiedermann
  • 4,317
  • 3
  • 24
  • 37