APIs & Integrations

mathiasklenk
Member

Getting Access Token & Refresh Token fails in NodeJS but successds in Postman

Hi,

I have a weird problem. When I try to use Oauth to get the access and refresh token for the code, it fails in node. But when I send exactly the same request out in Postman, I get a response that works. Please see my code:

 

 

const formData = {
      grant_type: "authorization_code",
      client_id: "XXXXX",
      client_secret: "XXXXX",
      redirect_uri: "XXXXX",
      code: XXXX,
    };

    const options = {
      method: "POST",
      url: "https://api.hubapi.com/oauth/v1/token",
      headers: {
        "content-type": "application/x-www-form-urlencoded;charset=utf-8",
      },
      form: JSON.stringify(formData),
    };
    request(options, function (error: any, response: any) {
      if (error) throw new Error(error);
      console.log(response.body);
    });

This leads to a response of this:

 

{"status":"BAD_GRANT_TYPE","message":"missing or unknown grant type","correlationId":"deaf1004-dcf0-4365-b36e-a64d2035b1e0","requestId":"3815493a-6286-4448-93d9-c943d58ddbf0"}

 

When I run this in Postman, like this:

Screen Shot 2020-04-23 at 5.05.45 PM.png

 

What am I doing wrong? My request is based on what Postman gave me and it seems correct.

0 Upvotes
2 Replies 2
WendyGoh
HubSpot Employee
HubSpot Employee

Getting Access Token & Refresh Token fails in NodeJS but successds in Postman

Hey @mathiasklenk,

 

When looking to POST data via node js, I believe you'd need to post the data by using the write request method i.e.

 

request.write(formData) 

 

instead of including it in the options JSON. 

0 Upvotes
mathiasklenk
Member

Getting Access Token & Refresh Token fails in NodeJS but successds in Postman

So I made it somehow work, but also didn't really know why. But in the end I used the official hubspot node package.

 

For any future readers, I highly recommend using the hubspot package and this function. This will save you a lot of headache. Here is the link for exchanging the code: https://github.com/MadKudu/node-hubspot#obtain-an-access-token-from-an-authorization_code