Search code examples
ajaxfirebaseelasticsearchherokubonsai-elasticsearch

Bonsai Elasticsearch add-on: 401 Unauthorised Error


In order to deploy my firebase application, which uses Elasticsearch I am looking at using Heroku Bonsai Add-on.

Everything is set, issue is I am getting an unauthorised error on passing Ajax request. Exactly the same code has been working smoothly on local (link) but not on deploying.

Ajax.jx

$(function() {
    $('#message').keyup(function() {
        var query = {
            "query": {
                "match": {
                    "song": {
                        "query": $("#message").val(),
                        "operator": "and"
                    }
                }
            }
        };

        $.ajax({
            type: "POST",
            url: "https://<username>:<password>@xxxwood-5671445.xx-xxxx-1.bonsaisearch.net/firebase/_search",
            contentType: 'application/json',
            crossDomain: true,
            data: JSON.stringify(query),
            success: searchSuccess,
            dataType: 'json'
        });

    });

});

I have used the correct username and password for my Bonsai URL but it's not working.

Console error: enter image description here

Chrome console error:enter image description here

cURL though works all right:

[~]$ curl -XGET 'https://<username>:<password>@dogwood-5671445.xx-xxxx-1.bonsaisearch.net/firebase/_search?pretty' -H 'Content-Type: application/json' -d'
{"query": {"match": {"song": {"query": "i am in", "operator": "and"}}}}'

cURL result:

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 1.4048493,
    "hits" : [ {
      "_index" : "firebase",
      "_type" : "song",
      "_id" : "0001",
      "_score" : 1.4048493,
      "_source" : {
        "song" : "i am in california",
        "song_name" : "hello",
        "song_url" : "https://xxx.xx/xxxx"
      }
    } ]
  }
}

Question: What am I missing?


Solution

  • Likely Ajax wasn't passing the credentials from the URL. Attach auth via HTTP header like so: How to use Basic Auth with jQuery and AJAX?