如何使用请求体发起GET请求

3
首先,我知道有一些可以使用的模块(https://www.npmjs.com/package/elasticsearch),但我正在寻找一种使用node.js内置模块来解决此问题的方法。
我正在寻找一种使用http模块在nodejs中执行以下curl请求的方法:
来源: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" }
    }
}'

例如,使用请求主体进行请求。
我按照手册中描述的编写了POST数据的方法:https://nodejs.org/api/http.html#http_http_request_options_callback
req.write(parsedData);
2个回答

6

以下是使用 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();

为了测试它,您可以使用以下命令在9200端口上启动netcat监听:

nc -l 9200

运行我的Node示例会发送以下请求:
GET /twitter/tweet/_count HTTP/1.1
Content-type: application/json
Host: localhost:9200
Connection: close

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

如果您不想使用任何npm模块,如request,那么您需要熟悉内置的http模块的低级API。可以参考以下链接进行详细了解:


数据事件是无关紧要的,我认为你误解了问题。 - superhero
@ErikLandvall 你是对的。我以为你想用curl发出请求,然后用Node获取它。我更新了我的答案。 - rsp
我不知道为什么,但是我通过运行示例仍然无法使其工作。 我甚至复制粘贴了你的示例代码.. 我仍然得到与没有正文时相同的响应.. 我开始觉得这与node.js无关 :( - superhero
2
我找到了问题,我忘记了Content-Length头。 - superhero
我知道这不是使用HTTP的常规方式,但这是ElasticSearch的工作方式。 - superhero
显示剩余5条评论

2

我稍微修改了rsp的答案,以支持https。

import https from 'https';
import http from 'http';

const requestWithBody = (body, options = {}) => {
  return new Promise((resolve, reject) => {
    const callback = function(response) {
      let str = '';
      response.on('data', function(chunk) {
        str += chunk;
      });
      response.on('end', function() {
        resolve(JSON.parse(str));
      });
    };

    const req = (options.protocol === 'https:' ? https : http).request(options, callback);
    req.on('error', (e) => {
      reject(e);
    });
    req.write(body);
    req.end();
  });
};

// API call in async function
const body = JSON.stringify({
  a: 1
});
const result = await requestWithBody(body, options = {
  host: 'localhost',
  port: '3000',
  protocol: 'http:', // or 'https:'
  path: '/path',
  method: 'GET',
  headers: {
    'content-type': 'application/json',
    'Content-Length': body.length
  }
};)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接