【问题标题】:vue js axios, send a POST to elasticsearchvue js axios,发送 POST 到 elasticsearch
【发布时间】:2020-10-16 12:00:21
【问题描述】:

在使用 Axios 的 Vue JS 中,我想向 Elasticsearch 实例发出 POST 请求。更准确地说,我想存储一个搜索模板 (https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html#pre-registered-templates)

POST _scripts/<templateid> {
    "script": {
        "lang": "mustache",
        "source": {
            "query": {
                "match": {
                    "title": "{{query_string}}"
                }
            }
        }
    } }

它适用于 CURL,但我在尝试使用 Axios 时收到错误 400。 我的代码如下(以test 作为模板ID)

var dataBody = {
        "script": {
          "lang": "mustache",
          "source": {
            "query": { 
              "match": {
                "keyword": {
                  "query": "{{search_term}}"
                }
              }
            }
          }
        }
      };

      this.$http.post(
        "https://es-url/_scripts/test",
        {
          contentType: "application/json; charset=utf-8",
          crossDomain: true,
          dataType: "json",
          headers: {
            Authorization: "Basic " + btoa("elastic:password")
          },
          params: {
            source: dataBody,
            source_content_type: 'application/json'
          }
        }
      )
      .then(response => {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

错误:

Error: Request failed with status code 400
    at createError (createError.js?2d83:16)
    at settle (settle.js?467f:17)
    at XMLHttpRequest.handleLoad (xhr.js?b50d:61)

我使用相同的 Axios 参数来检索数据(来自我的搜索查询),它工作得很好,不同之处在于我可以使用 GET 进行搜索查询,而我需要使用 POST 来存储搜索模板。

【问题讨论】:

  • 您确定您使用的是 Axios?这看起来更像是一个 jQuery $.ajax() 调用

标签: vue.js elasticsearch post axios


【解决方案1】:

看起来你把 Axios 和 jQuery 的 $.ajax 搞混了。

如果你实际使用的是Axios,它看起来像这样

this.$http.post('https://es-url/_scripts/test', dataBody, {
  auth: {
    username: 'elastic',
    password: 'password'
  }
})

请注意,要使其正常工作,您需要使用 http.cors.enabled=true 配置 Elasticsearch。见https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-http.html

【讨论】:

  • 谢谢你的回答,我需要执行 PUT _cluster/settings { "persistent" : { "http.cors.enabled" : true } } 我试过了,但我得到了 "persistent setting [http .cors.enabled],不可动态更新”。非常感谢您的帮助
  • @woshitom 我没有太多使用 Elasticsearch,但 http 设置应该在你的 configuration file 中设置,正如我在我的答案中链接的文档中所解释的那样
猜你喜欢
  • 2019-04-26
  • 1970-01-01
  • 2019-07-10
  • 2019-08-28
  • 2019-02-12
  • 2021-05-22
  • 2019-05-12
  • 2019-01-29
  • 1970-01-01
相关资源
最近更新 更多