Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS issue while making AJAX to elasticsearch on AWS

I have demo client in javascript that attempts to do a search on Elasticsearch that runs happily on Amazon AWS Cloud.

Thing is that I am getting the result back (fiddler shows it comes nicely in JSON, as it should be). But the browser is hitting me with this:

XMLHttpRequest cannot load http://ec2-xx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com:9200/pekara/hljeb/_search. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:7000' is therefore not allowed access.

This is the demo Ajax that I use:

  var searchString = "http://ec2-xx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com:9200/pekara/hljeb/_search";

        debugger;
        $.ajax({
            url: searchString,
            type: 'POST',
            contentType: 'application/json; charset=UTF-8',
            dataType: "json",
            crossDomain: true,
            data: JSON.stringify(data),
            success: function (data) {
                console.log("And this is success: " + data);

                $("#contentholder").text(data);
            }
        }).fail(function (error) {
            console.log("Search Failed")
        })
    }

So to repeat, Fiddler shows the result comes back, but browser points to fail method every single time. How to resolve CORS in this example?

The demo application is being server on Node.js.

This is content of my elasticsearch.yaml file:

The rest of the file is default, meaning everything is commented out:

    {
  "cluster.name": "Mycluster",
  "node.name": "My-node",
  "cloud": {
    "aws": {
      "access_key": "xxxxxxxxxxxxxxxxxxxxxx",
      "secret_key": "xxxxxxxxxxxxxxxxx"
    }
  },
  "discovery": {
    "type": "ec2",
          "ec2" : {
        "groups": "Elastic-Search-GROUP"
   }
 }
}


http.cors.allow-origin: true,
http.cors.allow-methods: true,
http.cors.allow-headers: true,
http.cors.allow-credentials: true,
http.cors.enabled: true
like image 974
Wexoni Avatar asked Dec 26 '22 02:12

Wexoni


1 Answers

CORS is implemented and applicable only to browsers and not apps (Fiddler/Rest Client et al)

Your server needs to allow the domains that are going to access the service via javascript. Configure your elastic search to do so. Update the http config to do so. Relevant properties: http.cors.enabled, http.cors.allow-origin, http.cors.allow-methods, http.cors.allow-headers, http.cors.allow-credentials

If you want to do it via the vm parameters, use these while starting the process:

elasticsearch -Des.http.<property1>=<val1> -Des.http.<property2>=<val2> ...

[EDIT]

Extend your .json file by adding this:

"http": {
    "cors.enabled" : true,
    "cors.allow-origin": "*"
}
like image 129
TJ- Avatar answered Feb 04 '23 07:02

TJ-