Cross-Origin Request Blocked

(Tony) #1

Hello,
I am attempting to access data from elasticsearch for use in D3. I am running elasticsearch and kibana in docker containers with ports 9200 and 5601 mapped to localhost:9200 and 5601 respectively, and am testing the html and script from a browser on a virtual linux machine that has the docker containers up and running.
I can access Kibana through the browser. However, when I load my custom page to perform the query, I get the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9200/file_index/_search. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

This is in spite of including the following lines in my elasticsearch.yml:

CORS settings.

http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-methods : OPTIONS, HEAD, GET, POST

The script attempting to perform the query is below.

//
// Performs a search request against an Elasticsearch server.
// @param {string} needle
// The string to search for.
// @param {string} filter
// A string to use to filter by type. For example: 'article';
//
function doSearch (needle) {
var searchHost = 'http://localhost:9200/file_index/_search';
var body = {
'size': 20
};

  var query = {
    'bool': {}
  };

    query.bool.must = {
      'multi_match': {
        'query': needle,
        'fields': [ 'UUID' ]
      }
    };

  body.query = query;

// Perform the request.
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('POST', searchHost, false);
xmlHttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xmlHttp.send(JSON.stringify(body));
var response = JSON.parse(xmlHttp.responseText);
// Print results on screen.
var output = '';
for (var i = 0; i < response.hits.hits.length; i++) {
  output += '<h3>' + response.hits.hits[i]._source.title + '</h3>';
  output += response.hits.hits[i]._source.summary_processed[0] + '</br>';
}
document.getElementById('total').innerHTML = '<h2>Showing ' + response.hits.hits.length + ' results</h2>';
document.getElementById('hits').innerHTML = output;

}
doSearch('ddbec291-574d-483f-b8d1-f88ea844c49b');

Any insights are appreciated.

(Tony) #2

Solved: The docker-compose.yml was misplacing the elasticsearch.yml file in the container running elasticsearch, so the CORS settings were not being seen by elasticsearch.

1 Like
(Mark Walkom) #3

Thanks for sharing your solution :slight_smile: