我正在尝试使用nodejs将文档索引到elasticsearch。我使用http library from node.js。当我执行我的测试时,我得到:
> node test2.js
data=(bodyText=bodytext)
STATUS: 400
HEADERS: {"content-type":"application/json; charset=UTF-8","content-length":"906"}
response: {"error":"ElasticSearchParseException[Failed to derive xcontent from (offset=0, length=17): [98, 111, 100, 121, 84, 101, 120, 116, 61, 98, 111, 100, 121, 116, 101, 120, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]","status":400}
但是,对curl的调用按预期工作:
curl -XPOST 'http://localhost:9200/google/mail' -d '{
"bodytext": "bodytext"
}'
{ok":true,"_index":"google","_type":"mail","_id":"DMJXn80xTmqdny9l6BwV7w","_version":1}
代码
// elasticsearch.js
http = require('http');
stringify = require('querystring').stringify;
exports.indexDocument = function(document) {
var data = stringify(document);
//data = document;
var options = {
host: 'localhost',
port: '9200',
path: 'google/mail',
method: 'POST'
};
var request = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (response) {
console.log('response: ' + response);
});
});
console.log('data=('+data+')');
request.write(data);
request.end();
}
// test2.js
completeMsg = {
bodyText: "bodytext"
};
require('./elasticsearch').indexDocument(completeMsg);
答案 0 :(得分:5)
在curl示例中,您正在发送JSON字符串,但在您的节点示例中,您正在发送一个查询字符串编码的字符串。我希望更换:
var data = stringify(document)
...与...
var data = JSON.stringify(document)
会做你想做的事。