1

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);  
  })
}
  • How confident are you in that Content-Type? Have you tried removing it or setting it to `application/json`? – Alexander Nied Jun 10 '20 at 14:58
  • yes i have tried setting it to application/json and i still get the same error as well as when i remove it i still get the same error. – Jessica Yip Jun 10 '20 at 15:08

1 Answers1

1

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}`
    },
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
  • when i took out the hyphen i ended up with a: script.js:43 POST https://accounts.spotify.com/api/token 400 error. The 415 error is no longer there. – Jessica Yip Jun 10 '20 at 15:42
  • @JessicaYip - Sounds like (hopefully) one error was resolved and another one was uncovered. There's [Github issue](https://github.com/spotify/web-api/issues/321#issuecomment-321134744) covering 400s-- looks like for many the solution was passing Grant Type as a param instead of in the body. Also, FWIW, it looks like [that API is perhaps not intended for consumption in the browser](https://stackoverflow.com/questions/53218678/spotify-api-bad-request-on-api-token-authorization-error-400); if you're including a client secret in browser code that's probably a security concern. – Alexander Nied Jun 10 '20 at 16:19
  • yes errors are slowly unraveling. i now get a 401 & 405 error with my Get requests. – Jessica Yip Jun 10 '20 at 17:57