在AWS上使用AJAX进行弹性搜索时出现CORS问题

Ved*_*ic. 4 amazon-web-services cors elasticsearch

我在javascript中有一个demo客户端试图在Elasticsearch上进行搜索,该搜索在Amazon AWS Cloud上运行愉快.

事情就是我得到了结果(fiddler在JSON中显示它很好,因为它应该是).但浏览器正在打击我:

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.
Run Code Online (Sandbox Code Playgroud)

这是我使用的演示Ajax:

  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")
        })
    }
Run Code Online (Sandbox Code Playgroud)

所以重复一遍,Fiddler显示结果返回,但浏览器每次都指向失败方法.在这个例子中如何解决CORS?

演示应用程序是Node.js上的服务器.

这是我的elasticsearch.yaml文件的内容:

文件的其余部分是默认的,这意味着所有内容都被注释掉了:

    {
  "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
Run Code Online (Sandbox Code Playgroud)

TJ-*_*TJ- 10

CORS实现并仅适用于浏览器而非应用程序(Fiddler/Rest Client等)

您的服务器需要允许通过javascript访问服务的域.配置弹性搜索以执行此操作.更新http配置以执行此操作.相关属性:http.cors.enabled,http.cors.allow-origin,http.cors.allow-methods,http.cors.allow-headers,http.cors.allow-credentials

如果要通过vm参数执行此操作,请在启动过程时使用这些参数:

elasticsearch -Des.http.<property1>=<val1> -Des.http.<property2>=<val2> ...
Run Code Online (Sandbox Code Playgroud)

[编辑]

通过添加以下内容扩展.json文件:

"http": {
    "cors.enabled" : true,
    "cors.allow-origin": "*"
}
Run Code Online (Sandbox Code Playgroud)

  • 坚持,稍等.现在,`*`表示允许所有来源访问您的es服务.但是,您应该通过限制域来保护它.为此,请在[allow-origin](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)中仅指定一组域.好吧,只有你想阻止它们. (2认同)