DavidShepard
DavidShepard

Reputation: 296

Node JS Needle Post Response Body Returned as Buffer

I am currently trying to call a remote API from a node.js application that I am writing using needle. The API requires that I make all requests as post requests. when I try to print out the response.body in the console log the only thing that prints out is <Buffer >.

My node.js code is as follows:

var needle = require('needle');
var options = {
    data: { "username": "**********", "password":"******************" },
    headers: {  "Accept":"application/json", "Accept-Encoding":"gzip,deflate", "Content-Type":"application/json" }
};
needle.post('http://www.linxup.com/ibis/rest/linxupmobile/map', options, function(err, resp, body) {
  // you can pass params as a string or as an object.
    console.log(body.toString());

Additionally I have tried printing resp, resp.body, body, and all of the aforementioned items with the .toString() method attached. I just want to be able to see the response data returned from the API POST call.

Upvotes: 0

Views: 3208

Answers (1)

DavidShepard
DavidShepard

Reputation: 296

The issue is that needle offers shortcuts to create a header for your REST requests. These were overriding my headers and caused a compressed response body to be returned. I simply removed my custom header and used Needle's format instead:

var options = {
    compressed: true,
    accept: 'application/json',
    content_type: 'application/json'
};

I then moved my body to a separate array:

var data = {
  "username": "***********", "password":"*********"
}

Finally I created the request:

needle.post('http://www.linxup.com/ibis/rest/linxupmobile/map', data, options, function(err, resp, body) {
...
}

this then allowed me to access the response body without issues.

Upvotes: 2

Related Questions