Erik Landvall Erik Landvall - 11 days ago 6
Node.js Question

How to make a GET request with body


Firstly, I understand that there are modules that could be used (https://www.npmjs.com/package/elasticsearch), but I'm looking for a way to solve this with node.js build in modules.


I'm looking for a way to do the following curl request in nodejs using the http module:

source: https://www.elastic.co/guide/en/elasticsearch/reference/2.4/search-count.html

curl -XGET 'http://localhost:9200/twitter/tweet/_count' -d '
{
"query" : {
"term" : { "user" : "kimchy" }
}
}'


E.g, making a request with a request body.




I have tried as described in the manual for writing post data: https://nodejs.org/api/http.html#http_http_request_options_callback

req.write(parsedData);

rsp rsp
Answer

Here is an example to make an HTTP GET request with a body using only the http module:

var http = require('http');

var options = {
  host: 'localhost',
  path: '/twitter/tweet/_count',
  port: '9200',
  method: 'GET',
  headers: {'Content-Type': 'application/json'}
};

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

var data = {a: 1, b: 2, c: [3,3,3]};
var json = JSON.stringify(data);
var req = http.request(options, callback);
req.write(json);
req.end();

To test it you can start netcat listening on port 9200 with:

nc -l 9200

Running my Node example sends the following request:

GET /twitter/tweet/_count HTTP/1.1
Content-type: application/json
Host: localhost:9200
Connection: close

{"a":1,"b":2,"c":[3,3,3]}

If you don't want to use any npm modules like request then you need to get familiar with the low-level API of the built-in http module. It is very well documented on:

Comments