Home > Software design >  Axios response.data weird characters
Axios response.data weird characters

Time:12-02

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

CodePudding user response:

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': '*'
    },
  })

CodePudding user response:

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

  • Related