为什么AngularJS在$http post request的data object的末尾添加冒号?

Why does AngularJS add colon in the end of data object in $http post request

本文关键字:添加 object data http post 为什么 request AngularJS      更新时间:2023-09-26

当尝试使用angular js $http向elasticSearch发送请求时,我得到一个"Unexpected token: "错误。

我的代码是这样的:

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":{
                "*":{}
            }
        }
   }
});

当在chrome控制台查看表单数据部分时,我看到json尾部冒号。

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

真奇怪。关于如何消除尾随冒号有什么想法吗?

对于遇到这种行为的人,

在我的情况下,这是因为我索引了一个错误的JSON结构的文档。当使用elasticSearch的批量索引选项时,具有无效结构的json将在没有警告的情况下被索引。

错误实际上是在响应中,而不是在http请求中。

尝试重新索引文档,这可能会解决这个问题。

在我们的例子中,它是http。post缺少HTTP标头"内容类型"它应该被设置为"application/json",如果它是张贴的。

如果你发布json,只需添加

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

作为post方法的第三个参数。所以是

$http.post( endpoint, json_payload, {headers:{'Content-Type': 'application/json'}} )