HubSpot / oauth-quickstart-nodejs

A Node JS app to get up and running with the HubSpot API using OAuth 2.0
82 stars 131 forks source link

I got a error when refresf token with axios #17

Open hmuschett opened 4 years ago

hmuschett commented 4 years ago

I am trying to use axios to connect the API, I can axios to get the all contacts but when a tying to refresh token a i got an error

` const refreshTokenProof = { grant_type: 'refresh_token', client_id: CLIENT_ID, client_secret: CLIENT_SECRET,
refresh_token: prevToken };

  const authRequest = {
    method: 'post',
    url: 'https://api.hubapi.com/oauth/v1/token',        
    headers: {            
        'Content-Type': 'application/x-www-form-urlencoded',
        'charset': 'utf-8'
    },
    data: refreshTokenProof
  }
  try {
   /* const responseBody = await request.post('https://api.hubapi.com/oauth/v1/token', {
      form: refreshTokenProof
    });
    console.log(responseBody);
    const tokens = JSON.parse(responseBody);
    console.log('se esta leyendo el responce');
    console.log(tokens);*/

    console.log('       > probando el refrescar token con axios');

    const responseBody = await axios(authRequest);
    console.log('       > probando el refrescar token con axios');
    console.log(responseBody);
    const tokens = responseBody.data;

    console.log('       > Received an access token and refresh token');
    return tokens.access_token;
  } catch (e) {
    console.error(`       > Error exchanging ${refreshTokenProof.grant_type} for access token`);
    console.log(e);
    return e.response;
}`

I have this error `config: { url: 'https://api.hubapi.com/oauth/v1/token', method: 'post', data: '{"grant_type":"refresh_token","client_id":"608b63bf-989d-49d0-b405-dade3e72c01e","client_secret":"73e64962-f1ee-4906-b48a-b97dfa46bc94","refresh_token":"ad148c58-7225-42a3-8ce2-a8a171140e74"}', headers: { Accept: 'application/json, text/plain, /', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'axios/0.19.2', 'Content-Length': 191 }, transformRequest: [ [Function: transformRequest] ], transformResponse: [ [Function: transformResponse] ], timeout: 0, adapter: [Function: httpAdapter], xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, validateStatus: [Function: validateStatus] }, request: ClientRequest { domain: null, _events: { socket: [Function], abort: [Function], aborted: [Function], error: [Function], timeout: [Function], prefinish: [Function: requestOnPrefinish] }, _eventsCount: 6, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: true, upgrading: false, chunkedEncoding: false, shouldKeepAlive: false, useChunkedEncodingByDefault: true, sendDate: false, _removedConnection: false, _removedContLen: false, _removedTE: false, _contentLength: null, _hasBody: true, _trailer: '', finished: true, _headerSent: true, socket: TLSSocket { _tlsOptions: [Object], _secureEstablished: true, _securePending: false, _newSessionPending: false, _controlReleased: true, _SNICallback: null, servername: null, npnProtocol: false, alpnProtocol: false, authorized: true, authorizationError: null, encrypted: true, _events: [Object], _eventsCount: 9, connecting: false, _hadError: false, _handle: null, _parent: null, _host: 'api.hubapi.com', _readableState: [Object], readable: false, domain: null, _maxListeners: undefined, _writableState: [Object], writable: false, allowHalfOpen: false, _bytesDispatched: 404, _sockname: null, _pendingData: null, _pendingEncoding: '', server: undefined, _server: null, ssl: null, _requestCert: true, _rejectUnauthorized: true, parser: null, _httpMessage: [Circular], read: [Function], _consuming: true, _idleNext: null, _idlePrev: null, _idleTimeout: -1,

    [Symbol(bytesRead)]: 838 },
 connection: 
  TLSSocket {
    _tlsOptions: [Object],
    _secureEstablished: true,
    _securePending: false,
    _newSessionPending: false,
    _controlReleased: true,
    _SNICallback: null,
    servername: null,
    npnProtocol: false,
    alpnProtocol: false,
    authorized: true,
    authorizationError: null,
    encrypted: true,
    _events: [Object],
    _eventsCount: 9,
    connecting: false,
    _hadError: false,
    _handle: null,
    _parent: null,
    _host: 'api.hubapi.com',
    _readableState: [Object],
    readable: false,
    domain: null,
    _maxListeners: undefined,
    _writableState: [Object],
    writable: false,
    allowHalfOpen: false,
    _bytesDispatched: 404,
    _sockname: null,
    _pendingData: null,
    _pendingEncoding: '',
    server: undefined,
    _server: null,
    ssl: null,
    _requestCert: true,
    _rejectUnauthorized: true,
    parser: null,
    _httpMessage: [Circular],
    read: [Function],
    _consuming: true,
    _idleNext: null,
    _idlePrev: null,
    _idleTimeout: -1,
    [Symbol(asyncId)]: 30,
    [Symbol(bytesRead)]: 838 },
 _header: 'POST /oauth/v1/token HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/x-www-form-urlencoded\r\nUser-Agent: axios/0.19.2\r\nContent-Length: 191\r\nHost: api.hubapi.com\r\nConnection: close\r\n\r\n',
 _onPendingData: [Function: noopPendingOutput],
 agent: 
  Agent {
    domain: null,
    _events: [Object],
    _eventsCount: 1,
    _maxListeners: undefined,
    defaultPort: 443,
    protocol: 'https:',
    options: [Object],
    requests: {},
    sockets: [Object],
    freeSockets: {},
    keepAliveMsecs: 1000,
    keepAlive: false,
    maxSockets: Infinity,
    maxFreeSockets: 256,
    maxCachedSessions: 100,
    _sessionCache: [Object] },
 socketPath: undefined,
 timeout: undefined,
 method: 'POST',
 path: '/oauth/v1/token',
 _ended: true,
 res: 
  IncomingMessage {
    _readableState: [Object],
    readable: false,
    domain: null,
    _events: [Object],
    _eventsCount: 3,
    _maxListeners: undefined,
    socket: [Object],
    connection: [Object],
    httpVersionMajor: 1,
    httpVersionMinor: 1,
    httpVersion: '1.1',
    complete: true,
    headers: [Object],
    rawHeaders: [Array],
    trailers: {},
    rawTrailers: [],
    upgrade: false,
    url: '',
    method: null,
    statusCode: 400,
    statusMessage: 'Bad Request',
    client: [Object],
    _consuming: true,
    _dumped: false,
    req: [Circular],
    responseUrl: 'https://api.hubapi.com/oauth/v1/token',
    redirects: [],
    read: [Function] },
 aborted: undefined,
 timeoutCb: null,
 upgradeOrConnect: false,
 parser: null,
 maxHeadersCount: null,
 _redirectable: 
  Writable {
    _writableState: [Object],
    writable: true,
    domain: null,
    _events: [Object],
    _eventsCount: 2,
    _maxListeners: undefined,
    _options: [Object],
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 191,
    _requestBodyBuffers: [],
    _onNativeResponse: [Function],
    _currentRequest: [Circular],
    _currentUrl: 'https://api.hubapi.com/oauth/v1/token' },
 [Symbol(outHeadersKey)]: 
  { accept: [Array],
    'content-type': [Array],
    'user-agent': [Array],
    'content-length': [Array],
    host: [Array] } },

response: { status: 400, statusText: 'Bad Request', headers: { date: 'Wed, 19 Feb 2020 11:28:27 GMT', 'content-type': 'application/json;charset=utf-8', 'content-length': '171', connection: 'close', 'set-cookie': [Array], 'x-trace': '2BCD7CC1CBB36E52107C649AFA5D6075822BBAD6A5000000000000000000', 'access-control-allow-credentials': 'false', 'cf-cache-status': 'DYNAMIC', 'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"', 'strict-transport-security': 'max-age=31536000; includeSubDomains; preload', server: 'cloudflare', 'cf-ray': '5677e5bd9ce0ff5c-MAD' }, config: { url: 'https://api.hubapi.com/oauth/v1/token', method: 'post', data: '{"grant_type":"refresh_token","client_id":"608b63bf-989d-49d0-b405-dade3e72c01e","client_secret":"73e64962-f1ee-4906-b48a-b97dfa46bc94","refresh_token":"ad148c58-7225-42a3-8ce2-a8a171140e74"}', headers: [Object], transformRequest: [Array], transformResponse: [Array], timeout: 0, adapter: [Function: httpAdapter], xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, validateStatus: [Function: validateStatus] }, request: ClientRequest { domain: null, _events: [Object], _eventsCount: 6, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: true, upgrading: false, chunkedEncoding: false, shouldKeepAlive: false, useChunkedEncodingByDefault: true, sendDate: false, _removedConnection: false, _removedContLen: false, _removedTE: false, _contentLength: null, _hasBody: true, _trailer: '', finished: true, _headerSent: true, socket: [Object], connection: [Object], _header: 'POST /oauth/v1/token HTTP/1.1\r\nAccept: application/json, text/plain, /\r\nContent-Type: application/x-www-form-urlencoded\r\nUser-Agent: axios/0.19.2\r\nContent-Length: 191\r\nHost: api.hubapi.com\r\nConnection: close\r\n\r\n', _onPendingData: [Function: noopPendingOutput], agent: [Object], socketPath: undefined, timeout: undefined, method: 'POST', path: '/oauth/v1/token', _ended: true, res: [Object], aborted: undefined, timeoutCb: null, upgradeOrConnect: false, parser: null, maxHeadersCount: null, _redirectable: [Object], [Symbol(outHeadersKey)]: [Object] }, data: { status: 'BAD_GRANT_TYPE', message: 'missing or unknown grant type', correlationId: '9aa42132-53f9-436e-98fd-4cdb96f3d86d', requestId: '8e44b98ec6e40c9b32445b23748665e0' } }, isAxiosError: true, toJSON: [Function] } `

hmuschett commented 4 years ago

I solved importing querystring and using it to parce a body data

data: querystring.stringify(refreshTokenProof),