CORS issue while making AJAX to elasticsearch on AWS

為{幸葍}努か 提交于 2019-12-22 08:57:07

问题


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

回答1:


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": "*"
}


来源:https://stackoverflow.com/questions/26798518/cors-issue-while-making-ajax-to-elasticsearch-on-aws

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!