我遇到了成功使用从带有jQuery的ElasticSearch服务器检索到的应用程序/ json答案的问题。 Firefox告诉我,我正在获得HTTP GET的有效200 OK答案,Firefox网络监视器可以正确解析JSON。然而,jQuery不会调用success / done回调,只会失败并且总是被调用。
ElasticSearch告诉我一个警告标题:
299 Elasticsearch-5.4.1-Unknown“不推荐使用静态请求的内容类型检测。使用[Content-Type]标头指定内容类型。” “周一,2017年7月3日07:59:32 GMT”
我一添加
var postData = {
"_source": ['title', 'url'],
"query" : {
"match": {
"body": "lorem"
}
},
"highlight" : {
"pre_tags" : ["<b>"],
"post_tags" : ["</b>"],
"fields" : {
"body" : {
"fragment_size" : 150,
"number_of_fragments" : 1,
"no_match_size": 150
}
}
}
};
function docsearch(){
var data = JSON.stringify(postData);
$.ajax({
//contentType:"application/json; charset=utf-8",
url: "http://127.0.0.1:9200/myindex/_search?pretty=true",
type: "POST",
dataType: "json",
data: data,
success: function (data) { console.log(data); }
}).done(function() {
alert( "success" );
})
.fail(function(data) {
console.log( data );
})
.always(function() {
alert( "complete" );
});
};
到$ .ajax()函数,Elasticsearch只返回一个空结果。
“有效”但不是回调版本的JS代码:
Host: 127.0.0.1:9200
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost/
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 208
Origin: http://localhost
DNT: 1
Connection: keep-alive
GET标题:
Content-Encoding: gzip
Content-Type: application/json; charset=UTF-8
Transfer-Encoding: chunked
Warning: 299 Elasticsearch-5.4.1-Unknown "Content type detection for rest requests is deprecated. Specify the content type using the [Content-Type] header." "Mon, 03 Jul 2017 07:59:32 GMT"
结果标题:
{
"took" : 3,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : 0.25124598,
"hits" : [
{
"_index" : "myindex",
"_type" : "post",
"_id" : "10",
"_score" : 0.25124598,
"_source" : {
"title" : "Lorem ipsum"
},
"highlight" : {
"body" : [
"<b>Lorem</b> ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat"
]
}
}
]
}
}
结果JSON:
09:59:32.973 Object { readyState: 0, getResponseHeader: .ajax/y.getResponseHeader(), getAllResponseHeaders: .ajax/y.getAllResponseHeaders(), setRequestHeader: .ajax/y.setRequestHeader(), overrideMimeType: .ajax/y.overrideMimeType(), statusCode: .ajax/y.statusCode(), abort: .ajax/y.abort(), state: .Deferred/e.state(), always: .Deferred/e.always(), catch: .Deferred/e.catch(), 9 more… }
失败回调的输出:
{{1}}
任何人都可以提供一些见解,为什么jQuery没有调用成功函数?我发现它可能与Transfer-Encoding有关:chunked。
由于
答案 0 :(得分:0)
抱歉打扰。答案确实是缺少Access-Control-Allow-Origin标头。因为它是POST,所以也需要允许:
Header set Access-Control-Allow-Origin "http://elasticsearch-host.domain"
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"