Issue in getting response from http call

Good morning,

This is my first assignment of Node-Red and I am creating a custom-node that will get data from an API. To get the data I need to send an access token from another host.

I am getting the access token through postman

but when I tried it through code it gives me no response (even if I pass the incorrect ClientSecret).

See my code below...

node.on('input', function(msg) {
      var http = require('http');
  var options = {
    host: 'hostname'
    path: '/master/protocol/openid-connect/token',
    headers: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    data: {
      grant_type:'client_credentials',
      client_id:'api',
      client_secret:'7*********-ebeb-472b-a61c-cb88959f682e',
      audience:'API_IDENTIFIER'       
    },
    method: 'POST'
  };

  callback = function(response) {
    var str = ''  
    response.on('data', function (chunk) {
      str += chunk;
      msg.payload = String(str); 
    });
    response.on('end', function () {
      console.log(str);
    });
  }

  var req = http.request(options, callback);

  req.on('error', function(e) {
    console.log('Error with the request:', e);
  });

  req.end();
 }

  node.send(msg);
});

My Output when running the flow...

Please suggest.

Solution:

Need to Stringify the body with the help of 'qs'.and did it with the help of node-fetch

const data = qs.stringify({
            grant_type: 'client_credentials',
            client_id: 'apicall',
            client_secret: '************-*************-************cb88959f682e'
        });
 
        const headers = {
            'content-type': 'application/x-www-form-urlencoded'
        }
        let token = "";

        var fetch = require("node-fetch");
        let url = 'https://***********************************/openid-connect/token';
        fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: data
        }).then(res => res.json().then(data => console.log(data.access_token)));

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.