2016-11-24 64 views
1

首先,據我所知,有一些可以使用的模塊(https://www.npmjs.com/package/elasticsearch),但是我正在尋找一種方法使用的是Node.js來解決這個構建模塊。如何使身體GET請求

我正在尋找辦法做到在使用http模塊中的NodeJS以下捲曲要求:
來源: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,使得與請求主體的請求。 https://nodejs.org/api/http.html#http_http_request_options_callback

req.write(parsedData); 

回答

2

這裏是使與身體僅使用http模塊的HTTP GET請求的例子::


作爲寫入後數據手冊中所描述我曾嘗試

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(); 

要測試它,您可以啓動netcat監聽端口9200:

nc -l 9200 

運行我的節點例如發送以下請求:

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

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

如果你不希望像request,那麼你需要熟悉的低級API使用任何NPM模塊內置http模塊。這是非常有據可查的:

+0

數據事件是無關緊要的,我想你missunderstood的問題。 – superhero

+0

我需要發送一個請求體中的問題描述,equalent到捲曲標誌'-d':https://curl.haxx.se/docs/manpage.html#-d – superhero

+0

相關:HTTP://計算器.COM /問題/ 978061/HTTP-GET-與請求體 – superhero