Jessica Yip
Jessica Yip

Reputation: 23

POST https://accounts.spotify.com/api/token 415 error when using fetch

I'm trying to make a request to get an authorization code from the spotify api using fetch but I keep getting a 415 error code. I did not have any errors when i was originally using $.ajax instead of fetch.

let client_id = '8f10fa8af1aa40c6b52073811460bf33'
let client_secret = '27a7c01912444b409a7f9a6d1f700868'
let ah = btoa(client_id + ":" + client_secret)

const getAuthToken = (searchedTerm) => {
fetch( `https://accounts.spotify.com/api/token`,
  {
    headers: {
      'Content-Type': 'application/x-www-form-url-encoded',
      'Authorization': `Basic ${ah}`
    },
    body: {
      grant_type: 'client_credentials'
    },
    json: true,
    method : "POST"
  }
)

  .then(function(response) { 
    authToken = response.access_token;
    spotifySearch(response.access_token, searchedTerm);  
  })
}

Upvotes: 1

Views: 973

Answers (1)

Alexander Nied
Alexander Nied

Reputation: 13678

See this answer on a similar post. Note that there they set 'Content-Type':'application/x-www-form-urlencoded', with no hyphen between url and encoded. I think you simply need to change

    headers: {
      'Content-Type': 'application/x-www-form-url-encoded',
      'Authorization': `Basic ${ah}`
    },

to

    headers: {
      'Content-Type': 'application/x-www-form-urlencoded', // no hyphen in urlencoded
      'Authorization': `Basic ${ah}`
    },

Upvotes: 1

Related Questions