【问题标题】:CORS issue while making AJAX to elasticsearch on AWS在 AWS 上将 AJAX 用于弹性搜索时出现 CORS 问题
【发布时间】:2015-01-04 02:00:50
【问题描述】:

我有一个 javascript 演示客户端,它尝试在 Elasticsearch 上进行搜索,该搜索在 Amazon AWS Cloud 上运行良好。

事情是我得到了结果(提琴手显示它在 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.

这是我使用的演示 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")
        })
    }

重复一遍,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

【问题讨论】:

    标签: amazon-web-services elasticsearch cors


    【解决方案1】:

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

    您的服务器需要允许要通过 javascript 访问服务的域。配置您的弹性搜索以执行此操作。更新http config 以执行此操作。相关属性:http.cors.enabledhttp.cors.allow-originhttp.cors.allow-methodshttp.cors.allow-headershttp.cors.allow-credentials

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

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

    [编辑]

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

    "http": {
        "cors.enabled" : true,
        "cors.allow-origin": "*"
    }
    

    【讨论】:

    • 所以我将这些属性添加到 elasticsearch.yaml 文件中?
    • 是的,这样会更好。
    • 一边说一边尝试 :)。将尽快发布结果
    • 我已将这些属性添加到 elasticsearch.yaml 并重新启动服务器。还是一样的问题。
    • 等一下。现在,* 表示允许所有源访问您的 es 服务。但是,您应该通过限制域来保护它。为此,请在 allow-origin 中仅指定一组域。好吧,只有当你想阻止它们时。
    猜你喜欢
    • 2023-02-06
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多