Search code examples
javascriptreactjsaxiosspotify

Spotify/axios question for my first solo project (noob question)


This is probably a silly question - I only started learning code in September and this is my first solo project in React (or at all really).

I hit a wall on my first build trying to make a POST request to the Spotify API to get back an access token:

https://developer.spotify.com/documentation/general/guides/authorization/client-credentials/

I keep getting error 415 with this request and I am using the 'Content-Type' : 'application/x-www-form-urlencoded' as they reccomended in the Spotify API docs.

Any help would be so appreciated!

export const SpotifyAPI = () => {

const buffer = new Buffer.from(`${client_id}:${client_secret}`);

  axios.post(
    'https://accounts.spotify.com/api/token', {
        form: { grant_type: 'client_credentials' },
        headers: {
            Authorization: 'Basic' + buffer.toString('base64'),
            'Content-Type': 'application/x-www-form-urlencoded',
        },
    }).then(response => console.log(response));


Solution

  • Axios doesn't have a form option. The body of the request goes in the data parameter. And you have to convert the data to a string if you want URL encoded data, you can't just pass an object.

    There is a HOWTO for this in the axios documentation.


    this is my first solo project in React

    React generally runs client-side in the browser. The documentation you link to says:

    The Client Credentials flow is used in server-to-server authentication.

    It is not intended for user in the browser and trying to do so is likely to run into CORS errors and leak your client secret to every visitor to your website.