Issues requesting new token through Node.js

(John Bramley) #1

I’m working on setting up an automatic renewal of my API token through my app, but am unable to successfully do so except by copying the CURL example in the FAQ. My axios request looks like this:

function renewBearerToken() {
  var config = { headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Accept": "application/json"
  }};
  var data = { params: {
    grant_type: 'client_credentials',
    client_id: process.env.TCG_CLIENT_ID,
    client_secret: process.env.TCG_CLIENT_SECRET
  }};  
  return axios.post('https://api.tcgplayer.com/token', data, config)
  .then(response => {
    console.log(response);
    return response;
  })
  .catch(error => {
    console.log(error);
  });
};

Which I’m pretty sure contains everything needed, I’ve also tried submitting the post as one long string instead of with the data object. I’ve checked that my environmental variables are accurately set and was able to successfully renew using them + a curl request, so I know that they’re valid. Anyone know what I’m doing wrong?

(Joshua Burdick) #2

In curl it looks like this:

--data-binary "grant_type=client_credentials&client_id=PUBLIC_KEY&client_secret=PRIVATE_KEY" \

Instead of passing POST parameters it’s passed in the body. This stackoverflow goes into more detail about it with Node.js:

(John Bramley) #3

Thanks, moving the params to the body and stripping encoding did the trick. For anyone else using axios this is what got it working for me:

function renewBearerToken() {
  var body = `grant_type=client_credentials&client_id=${process.env.TCG_CLIENT_ID}&client_secret=${process.env.TCG_CLIENT_SECRET}`;
  return axios.post('https://api.tcgplayer.com/token', body, { headers:{'Content-Type' : 'text/plain' }})
  .then(response => {
    var token = response.data.access_token;
    var expires = response.data['.expires'];
    //do more stuff here
  })
  .catch(error => {
    console.log(error);
  });
};
1 Like