提问者:小点点

松紧带 CORS 绝望


我在本地环境中安装了ES5.4,我尝试使用ajax请求(使用jQuery)从我的Web浏览器向API发出请求,CORS策略破坏了它。

我阅读了ES HTTP文档和一些论坛,但我无法解决我的问题。

下面是我的elasticsearch.yml http conf:

http.port: 9200
http.cors.allow-origin: "*"
http.cors.allow-methods: X-Requested-With, Content-Type, Content-Length
http.cors.enabled: true
network-host: localhost

以下是我的请求参数:

// simple query string 
var queryFilter = {
  "query": {
    "match":  {
      "id_opp":"OPP_4"
    }
  }
};

jQuery.support.cors = true;

$.ajax({
  type: "POST",
  url: "http://localhost:9200/_search",
  crossDomain: true,
  data: JSON.stringify(queryFilter),
  dataType: "json",
  success: function(data): {console.log(data)}
  }, 
  error: function(xhr){console.log(xhr)}
);

这是来自浏览器的结果:Code POST 200 OK

在浏览器网络工具中,我在结果中得到了一些对象,这很好,但我的 JavaScript 代码将 ajax 结果读取为失败:

"
xhr.status文本:"错误"
成功:空

你能帮我在ajax请求中获得成功结果吗?

她是我的回应:

{
    "took": 33,
    "timed_out": false,
    "_shards": {
        "total": 10,
        "successful": 10,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 6,
        "max_score": 1.2438203,
        "hits": [{
                "_index": "opportunites",
                "_type": "opportunity",
                "_id": "OPP_4-10_LT_26173_MCHE_002",
                "_score": 1.2438203,
                "_source": {
                    "@version": "1",
                    "id_opp": "OPP_4-10_LT_26173_MCHE_002",
                    "@timestamp": "2017-11-03T16:17:24.852Z",                    
                    "commune": "CHARPEY"
                }
            },
        }]
}
}

删除后Chrome

crossDomain:真的,

并从 .yml 中删除:

http.cors.allow方法:X请求,内容类型,内容长度

我收到以下消息:

无法加载 http://localhost:9200/_search:请求的资源上不存在“访问控制允许源”标头。因此,不允许访问源“http://localhost:90”。

这是相应的响应标头:

HTTP/1.1 200 OK警告:299 Elasticsearch-5.6.3-1a2f265“不推荐对rest请求进行内容类型检测。请使用[Content type]标头指定内容类型。”“2017年11月7日星期二11:51:24 GMT”内容类型:application/json;charset=UTF-8内容编码:gzip内容长度:6898

插入内容类型后(已经测试过):

content type:" application/JSON;charset=UTF-8”,

我收到这个新错误:

无法加载http://localhost:9200/_search:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-origin”标头。因此,现在允许访问源“http://localhost:90”。

但我的elasticsearch.yml包含:

http.cors.allow-来源:"*"http.cors.enabled:true


共1个答案

匿名用户

最终我解决了我的问题!感谢ADyson的支持;)

这是我的超文本传输协议配置(elasticsearch.yml):

http.port:9200
http.cors.allow-origin: "*"
http.cors.allow-methods: Origin, X-Requested-With, Content-Type, Content-length, Accept
http.cors.enabled: true

这是我请求弹性搜索数据的JavaScript代码:

jQuery.support.cors = true;
// execute request
$.ajax({
    type: "POST",
    url: "http://localhost:9200/_search",
    data: JSON.stringify(queryFilter), // elastic filter
    dataType: "json",
    contentType: "application/json;charset=UTF-8",
    processData: false,
    success: function(data) {
        console.log(data)
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(xhr);
    }
});