node.js - 从 0.10.40 升级后 Node HTTP 删除请求不再有效

标签 node.js http elasticsearch

我一直在尝试将我的大部分 Node 升级到 4.x,但在执行对 Elasticsearch 的删除查询时遇到了一些问题。以下内容适用于 0.10.40 及之前版本,但不适用于 4.x.x 或 5.7.0。我没有主意, Node 似乎没有发送我的请求正文,因为我从 Elasticsearch 返回的错误是 {"error":"ActionRequestValidationException[Validation Failed: 1: source is missing;] ","status":400}.

var http = require('http');
var request = http.request({
    host: 'localhost',
    port: 9200,
    path: 'test/col/_query',
    method: 'DELETE'
});

request.on('response', function(res) {
    res.setEncoding('utf8');
    res.on('data', function(response) {
        if(response.indexOf('"failed":0') === -1) {
            console.log('Failed. Response: ', response);
            process.exit(1);
        }
    });
    res.on('end',  function() {
        console.log('completed successfully');
        process.exit(0);
    });
});
request.on('error', function(err) { cb(err); });

var q = {
    query: {
        "bool": {
            "must_not": [
                {"ids": {"values": ['1','2','3'] } }
            ]
        }
    }
};

request.write(JSON.stringify(q));
request.end();

最佳答案

HTTP DELETE 请求不应包含负载。但是,在 0.10 中,由于 Transfer-Encoding: Chunked HTTP header 会随请求一起发送,即使没有有效负载发送到服务器,它也得到了支持。这已在 0.11.14 中修复通过 issue 6164 .

从现在开始,如果您真的需要发送带有 DELETE 请求的正文,您还需要添加一个 Content-Length header 来指定您要发送的内容的长度,否则服务器将忽略任何有效负载。

因此,如果您这样构造您的请求,它将起作用:

var q = {
    query: {
        "bool": {
            "must_not": [
                {"ids": {"values": ['1','2','3'] } }
            ]
        }
    }
};
var payload = JSON.stringify(q);

var request = http.request({
    host: 'localhost',
    port: 9200,
    path: 'test/col/_query',
    method: 'DELETE',
    headers: {                                    <--- add this
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(payload)
    }
});

...

request.write(payload);
request.end();

关于node.js - 从 0.10.40 升级后 Node HTTP 删除请求不再有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35589109/

相关文章:

javascript - 如何替换node.js REDIS中已弃用的HMSET

python - 我可以使用带有 http-gzip 或 deflate 压缩的 python 请求库发布数据吗?

c# - 在NEST 2.0中找不到Add()方法

amazon-web-services - AWS API Gateway 和 Elastic Cloud 托管的 Elasticsearch 之间的身份验证

javascript - API 请求适用于 postman,但不适用于 Node.js(请求)

node.js - pg-promise 多个 OR in where 子句

linux - 千个并发请求 - EAI_AGAIN/ECONNRESET 错误

ruby - Rack 缓存有问题的缓存

html - HTTP header - 硬刷新 JavaScript/CSS

elasticsearch - 弹性查询 DSL : Wildcards in terms filter?