简体   繁体   中英

Axios post call for Spotify API authentication flow returning response code 400 for authentication call

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?

The row of Authorization in your code is totally wrong. The word 'Authorization' needs to be a string, not a variable.
Also, you are using the ` symbols wrong. In your code, the first opens a string, the second symbol closes the first, the third symbol opens the second string, and the fourth symbol closes the second string.
Lastly, I don't know what you are trying with the first $( .

The following code should work:

var axios = require('axios');

var client_id = 'CLIENT_ID';
var client_secret = 'CLIENT_SECRET';

var authOptions = {
  url: 'https://accounts.spotify.com/api/token',
  headers: {
    'Authorization': 'Basic ' + (Buffer.from(client_id + ':' + client_secret).toString('base64'))
  },
  data: {
    grant_type: 'client_credentials'
  }
};

axios.post(authOptions.url, authOptions.data, {headers: authOptions.headers})
  .then(function (response) {
    if (response.status === 200) {
      var token = response.data.access_token;
    }
  })
  .catch(function (error) {
    // handle error
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM