woshitom
woshitom

Reputation: 5129

vue js axios, send a POST to elasticsearch

In Vue JS using Axios I'd like to make a POST request to an Elasticsearch instance. More precisely I'd like to store a search template (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}}"
                }
            }
        }
    } }

It works with CURL but I'm getting an error 400 when I'm trying with Axios. My code is the following (with test as templateid)

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:

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)

I'm using the same Axios parameters to retrieve data (from my search queries), it works just fine, the difference is I can use GET for my search queries while I need to use POST to store a search template.

Upvotes: 0

Views: 1225

Answers (1)

Phil
Phil

Reputation: 164731

Looks like you've got Axios and jQuery's $.ajax mixed up.

If you are actually using Axios, it would look like this

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

Note that for this to work, you would need Elasticsearch configured with http.cors.enabled=true. See https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-http.html

Upvotes: 1

Related Questions