简体   繁体   中英

Node.js https.request method using client credentials

I am trying to make a request for an access token using https.request but I keep getting the following error:

"error":"invalid_request","error_description":"Missing grant type"

In the Node.js HTTPS.Request documentation there isn't any reference for how to set the grant type. I believe I need to set it in the body of the request, but there is also no reference to attaching a body to the request. I am attempting to do it with the payload variable but obviously that isn't working. I am also trying to do this request with 0 or as little dependencies as possible.

  function getAccessToken() {
   const https = require('https')
   const payload = {
    "grant_type": "client_credentials"
   }
  const options = {
    "hostname": url,
    "method": "POST",
    "path" : "/oauth2/token",
    "port" : 443,
    "encoding": "utf8",
    "followRedirect": true,
    "headers": {
      "Authorization": "Basic <base64 encoded client_id:client_secret>",
      "scope": "PARTNER_READ"
    },
    "payload": payload,
    'muteHttpExceptions': true
  }
  const req = https.request(options, res => {
    console.log(`statusCode: ${res.statusCode}`)
    res.on('data', d => {
      process.stdout.write(d)
    })
  })
  req.on('error', error => {
    console.error(error)
  })
  req.end()
}

Any help would be appreciated!

Just to close the loop on this, I was missing the 'Content-Type' in the header which I think was causing the "Missing Grant Type" error because it couldn't parse the body. I also needed to write the postData to the request right before the req.end(). So thank you @Klaycon for that point in the right direction!

Here is my updated code:

  function getAccessToken() {
     const querystring = require('querystring');
     const https = require('https')
     const postData = querystring.stringify({
         'grant_type': 'client_credentials'
     });

  const options = {
    "hostname": url,
    "method": "POST",
    "path" : "/oauth2/token",
    "port" : 443,
    "encoding": "utf8",
    "followRedirect": true,
    "headers": {
      "Authorization": "Basic <base64 encoded client_id:client_secret>",
      "Content-Type": 'application/x-www-form-urlencoded',
      "Content-Length": Buffer.byteLength(postData),
    },
    'muteHttpExceptions': true
  }
  const req = https.request(options, res => {
    console.log(`statusCode: ${res.statusCode}`)
    res.on('data', d => {
      process.stdout.write(d)
    })
  })
  req.on('error', error => {
    console.error(error)
  })
  req.write(postData);
  req.end()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM