2
router.get('/spotifyLogin', (req,res) => {
    const state = generateRandomString(16);
    const scope = 'user-read-recently-played';
    const queryParams = querystring.stringify({
        response_type: 'code',
        client_id: client_id,
        scope: scope,
        redirect_uri: redirect_uri,
        state: state
      });
    
    res.redirect(`https://accounts.spotify.com/authorize?${queryParams}`);
});

router.get('/callback', (req,res) => {

    
    const authorizationCode = req.query.code || null;
    const state = req.query.state || null;

    axios({
        method: 'post',
        url: 'https://accounts.spotify.com/api/token',
        data: querystring.stringify({
          grant_type: 'authorization_code',
          code: authorizationCode,
          redirect_uri: redirect_uri,
        }),
        headers: {
          'content-type': 'application/x-www-form-urlencoded',
          Authorization: `Basic ${new Buffer.from(`${client_id}:${client_secret}`).toString('base64')}`,
        },
      })
        .then(response => {
          if (response.status === 200) {
            res.send(response.data)
        
          } else {
            res.send(response);
          }
        })
        .catch(error => {
          res.send(error);
        });
});

I am doing the spotify authorization code flow on a custom express api server https://developer.spotify.com/documentation/general/guides/authorization/code-flow/

When I make a post request to the token url, I should get a json object in my response.data, but I am getting weird characters Screenshot of response.data

Jayden Yu
  • 41
  • 3

3 Answers3

6

Setting the accept-encoding header to * for the axios request solved it for me.

In your case, should look something like this:

axios({
  method: 'post',
  url: 'https://accounts.spotify.com/api/token',
  data: querystring.stringify({
    grant_type: 'authorization_code',
    code: authorizationCode,
    redirect_uri: redirect_uri,
  }),
  headers: {
    'content-type': 'application/x-www-form-urlencoded',
    Authorization: `Basic ${new Buffer.from(`${client_id}:${client_secret}`).toString('base64')}`,
    'accept-encoding': '*'
  },
})
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
anshai
  • 61
  • 1
2

This is a bug related to the axios version 1.2.0 . You can fix this by downgrading axios to 1.1.3. More information about this bug: https://github.com/axios/axios/issues/5298

Charlie
  • 65
  • 6
  • man thanks, I was spending two days on this one without realizing it was an issue with Axios. – Nithur Dec 02 '22 at 07:00
1

Yes, this is a bug in "axios": "1.2.0". Check this issue.

Adding 'accept-encoding': '*' to the headers fixed it.

Refer this documentation, to understand accept-encoding.

lenikhilsingh
  • 553
  • 2
  • 7
  • 20