1

When trying to use angular js $http to post a request to elasticSearch I get an "Unexpected token : " Error.

My code looks like this:

var request= $http({
    method: "post",
    url: path,
    accept:"*/*",
    headers:{"Content-Type" : "application/x-www-form-urlencoded; charset: UTF-8"},
    data:{
         "query":{
               "fuzzy":{
                    "title":{
                        "value": $scope.searchTerm,
                        "fuzziness":"1"
                    }
                }
        },
        "highlight":{
            "fields":{
                "*":{}
            }
        }
   }
});

When looking in the form data section on chrome console I see the json with a trailing colon.

[{"query":{"fuzzy":{"title":{"value": $scope.searchTerm,"fuzziness":"1"}}},
"highlight":{"fields":{"*":{}}}}]:    <--- this is the problem

That is strange. Any ideas on how to eliminate the trailing colon?

Itzik Gili
  • 324
  • 3
  • 16
  • Have you checked using advanced rest client or postman to see whether posted data does have trailing colon ? – road2victory Sep 03 '15 at 12:50
  • I'm pretty confident that Angular does not erroneously append such a thing. But looking at the code, I think the problem might be elsewhere. Did you really mean to mark that as form encoded via the headers? If you need form encoded, there are more hoops to jump through. See this. http://stackoverflow.com/questions/24710503/how-do-i-post-urlencoded-form-data-with-http-in-angularjs – Kyle Cordes Sep 03 '15 at 13:16
  • Yes, I checked with another rest client , the collon did not apear. – Itzik Gili Sep 03 '15 at 14:06
  • Kyle, I tried without the headers, did not help. – Itzik Gili Sep 03 '15 at 14:07
  • Have you tried building the object more explicitly as an object outside of the request? Perhaps in a function on the scope or something just as a test? var do = new Object(); do.query.fuzzy.title.value=$scope.searchTerm; do.query.fuzzy.title.fuzziness = "1"; etc, etc? It would be a good test to determine if the problem is in how you construct the object rather than what angular is doing with it. – tokkov Sep 03 '15 at 17:33

2 Answers2

1

For anyone who encounter this kind of behavior,

In my case it was because I indexed a document with wrong JSON structure. When using the bulk indexing option with elasticSearch - JSONs with invalid structure are indexed without warning.

The error was actually in the response , not on the http request.

Try re-indexing the document which will probably fix this issue.

Itzik Gili
  • 324
  • 3
  • 16
0

In our case it was that the http.post was missing HTTP header "content type" that should be set to "application/json", it that is was is posted.

If your posting json, just add

{headers:{'Content-Type': 'application/json'}}

as third parameter of the post method. So it is

$http.post( endpoint, json_payload, {headers:{'Content-Type': 'application/json'}} )
Kalle
  • 452
  • 2
  • 4
  • 19