已启用Elasticsearch https cors但仍未获得No' Access-Control-Allow-Origin'标头出现在请求的资源上

时间:2016-04-19 18:04:43

标签: javascript http elasticsearch cors

我已经在名为myIndex的索引中启用了cors的设置,以下是它的设置。但是当我尝试使用一些简单的Javascript从elasticsearch中提取数据时,我设置了错误

XMLHttpRequest无法加载http://elasticSearchDomain.com:9200/myIndex/_search/。对预检请求的响应没有通过访问控制检查:否'访问控制 - 允许 - 来源'标头出现在请求的资源上。起源' http://localhost:8000'因此不允许访问。

我正在运行Javascript,将其包含为通过python服务器打开html页面时运行的脚本。

var url = "http://elasticSearchDomain.com:9200/myIndex/_search/";
var method = "POST";
var postData = '{"query": { "filtered": { "query": { "query_string": { "query": "*", "analyze_wildcard": true } }, "filter": { "bool": { "must": [ { "query": { "query_string": { "query": "*", "analyze_wildcard": true } } }, { "range": { "report_time": { "gte": 1458409392443, "lte": 1461001392443 } } } ], "must_not": [] } } } }, "size": 0, "aggs": { "2": { "date_histogram": { "field": "report_time", "interval": "12h", "pre_zone": "-07:00", "pre_zone_adjust_large_interval": true, "min_doc_count": 1, "extended_bounds": { "min": 1458409392443, "max": 1461001392443 } }, "aggs": { "3": { "terms": { "field": "pool_name", "size": 20, "order": { "_count": "desc" } } } } } } }';

// You REALLY want async = true.
// Otherwise, it'll block ALL execution waiting for server response.
var async = true;

var request = new XMLHttpRequest();

// specifies how the HTTP response will be handled. 
request.onload = function () {

   // You can get all kinds of information about the HTTP response.
   var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
   var data = request.responseText; // Returned data, e.g., an HTML document.
}

request.open(method, url, async);
request.setRequestHeader('Access-Control-Allow-Headers', '*');
request.setRequestHeader('Access-Control-Allow-Origin', '*');
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

// Actually sends the request to the server.
request.send(postData);

这是我试图用来从elasticsearch

中提取数据的Javascript
Post.uncached do
  Post.where(user_id: nil, organization_id: nil).find_each do |posts|
    puts "** Updating batch beginning with post #{posts.first.id}..."

    # Update 1000 records at once
    posts.map!(&:id) # posts is an array, not a relation
    Post.where(id: posts).
      joins("INNER JOIN users ON (posts.user_name = users.user_name)").
      joins("INNER JOIN organizations ON (organizations.id = users.organization_id)").
      update_all("posts.user_id = users.id, posts.organization_id = organizations.id")

    puts "** Finished batch."
  end
end

2 个答案:

答案 0 :(得分:2)

这些不是特定于索引的设置。

cors设置应放在ES群集中​​每个节点的elasticsearch.yml配置文件中,并重新启动群集。有关详情,请参阅here

答案 1 :(得分:1)

对于某些特异性(以及任何遇到正则表达式部分问题的人),我必须在elasticsearch.yml中添加这些配置:

http.cors.enabled: true
http.cors.allow-origin: /https?:\/\/(localhost)?(127.0.0.1)?(:[0-9]+)?/

不完美正则表达式,但我的搜索应用程序现在正常运行。