0

I am a beginner with nodeJS.

What I am trying to do:

I have a POST API hosted and when I call it using postman, it gives me proper response as shown in image below:

enter image description here

But when I try to hit it using the NodeJS node-rest-client (https://www.npmjs.com/package/node-rest-client) it is giving me an irrelevant large object as below:

IncomingMessage {
  _readableState: 
   ReadableState {
     objectMode: false,
     highWaterMark: 16384,
     buffer: BufferList { head: null, tail: null, length: 0 },
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: true,
     ended: true,
     endEmitted: true,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: false,
  domain: null,
  _events: 
   { end: [ [Function: responseOnEnd], [Function] ],
     data: [Function],
     error: [Function] },
  _eventsCount: 3,
  _maxListeners: undefined,
  socket: 
   Socket {
     connecting: false,
     _hadError: false,
     _handle: null,
     _parent: null,
     _host: null,
     _readableState: 
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [Object],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,

I need help to get my proper object and I am not able to figure out what I am doing wrong here.

Below is my code to call REST API:

app.get('/notes', cors(), function(req, res) {

    var args = {
                "hiveMachineIp": "192.168.0.110",
                "hiveMachinePort": "10000",
                "hiveUsername": "nt",
                "hivePassword": "",
                "hiveDatabaseName": "default",
                "hiveTableName": "transactions_24m",
                "hiveAggregationColumn": "customerid",
                "hiveAggregationFunction": "HISTOGRAM",
                "hiveAggregationHistogramBin": "5"
            };

    var Client = require('node-rest-client').Client;

    var client = new Client();

    client.post("http://163.47.152.170:8090/MachinfinityDataPreparation/machinfinitydataprep/hiveDataAggregation/", args, function (data, response) {
        // parsed response body as js object 
        // console.log(data);
        // raw response 
        console.log(response);
    });

    // registering remote methods 
    client.registerMethod("postMethod", "http://163.47.152.170:8090/MachinfinityDataPreparation/machinfinitydataprep/hiveDataAggregation/", "POST");

    client.methods.postMethod(args, function (data, response) {
        // parsed response body as js object 
        // console.log(data);
        // raw response 
        console.log(response);
    });

})
Karthik Nagaraj
  • 143
  • 2
  • 13
  • My guess would be that you're somehow dumping the client, not the response from the server that client is receiving. If you don't mind share part of your client code that is responsible for creating rest client and the request. – Mr_KoKa Apr 16 '17 at 12:01
  • Issue is resolved using axios but I would still like to know what's wrong in above code. – Karthik Nagaraj Apr 16 '17 at 13:16

2 Answers2

0

You can use axios like this.

axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});
Sangwon Kim
  • 178
  • 2
  • 7
  • This did work for me. But, what's the reason that earlier it did not work if anyone can explain? – Karthik Nagaraj Apr 16 '17 at 13:05
  • @AnKarthik Because you try to print raw response data. It contains every infomation and data related to your request and response. – Sangwon Kim Apr 16 '17 at 22:46
  • @AnKarthik If you want to get response body data only, make uncomment `console.log(data)` and remove `console.log(response)` in your code – Sangwon Kim Apr 16 '17 at 22:55
0

Inside your code you're doing your request twice, once by client.post then by calling client.methods.postMethod that was previous registered. You should do one or the other, and response variable in each of callbacks comes from http client and it is not your raw json response. Your data has been already parsed and it sits in data variable.

In order to send one post request to your rest server you should use either client.post or register your method by client.registerMethod and then client.methods.registeredMethodName to send request.

When you need to send the same post request multiple times in your code then define a function that will handle response for that request, for instance:

function handleResponseA(data, response) {
    if(response.statusCode == 200){
        console.log(data);
    } else {
        switch(response.statusCode){
            case 404:
                console.log("Page not found.");
            break;

            case 500:
                console.log("Internal server error.");
            break;

            default:
                console.log("Response status code: " + response.statusCode);
        }
    }
}

And then for client.post:

client.post("http://163.47.152.170:8090/MachinfinityDataPreparation/machinfinitydataprep/hiveDataAggregation/", args, handleResponseA);
client.post("http://163.47.152.170:8090/MachinfinityDataPreparation/machinfinitydataprep/hiveDataAggregation/", args, handleResponseA);

And to accomplish it by registered method, register method by:

client.registerMethod("postMethod", "http://163.47.152.170:8090/MachinfinityDataPreparation/machinfinitydataprep/hiveDataAggregation/", "POST");

And then invoke registered method:

client.methods.postMethod(args, handleResponseA);
client.methods.postMethod(args, handleResponseA);
Mr_KoKa
  • 598
  • 4
  • 13