0

Here is my code:

const axiosInstance = axios.create({
  headers: {
    Authorization: `Basic ${Buffer.from(`${client_id}:${client_secret}`).toString('base64')}`,
  },
  form: {
    grant_type: 'client_credentials',
  },
  json: true,
});

const authFlow = async () => {
  try {
    const { response } = await axiosInstance.post('https://accounts.spotify.com/api/token');
    return response;
  } catch (error) {
    console.log(error.message);
    throw new Error(error);
  }
};

This is almost copy and pasted off of the documentation: https://developer.spotify.com/documentation/general/guides/authorization/client-credentials/ I think there is something wrong with the formatting of the axios call, but not sure what. The error message just says "Request failed with status code 400". Any ideas on what I'm doing wrong?

decheftw
  • 69
  • 6

1 Answers1

0

This code will give an access token from Spotify.

Demo code

Save as get-token.js file.

const axios = require('axios')
const base64 = require('base-64');

const getToken = async () => {
    try {
        const URL='https://accounts.spotify.com/api/token'
        const client_id = '******** your client id ********'
        const client_secret = '******** your client secret ********'
        const response = await axios.post(URL,
            new URLSearchParams({
                'grant_type': 'client_credentials'
            }),
            {
                headers:
                {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': 'Basic ' + base64.encode(client_id + ":" + client_secret)
                }
            })
        return Promise.resolve(response.data.access_token);
    } catch (err) {
        return Promise.reject(error);
    }
};

getToken()
    .then(token => {
        console.log("access token: " + token)
    })
    .catch(error => {
        console.log(error.message);
    });

Install dependencies

npm install axios base-64

Run it

node get-token.js

Result from terminal

enter image description here

References

How do I send a fetch request to Paypal's Oath API (v2)?

Spotify API curl example

Expo auth session spotify get refresh token

Bench Vue
  • 5,257
  • 2
  • 10
  • 14