问题描述
我正在尝试使用GET request
进行以下angular httpClient
的操作,但到目前为止没有成功。任何人都可以帮忙。请求如下。
curl --location --request GET 'MY_URL_TO_SEND'
--header 'Content-Type: application/json'
--header 'Authorization: MY_TOKEN'
--data-raw '{
"_source": ["title"],"query": {
"multi_match": {
"query": "covid","type": "best_fields","fields": ["title.e_ngrams^4","description.e_ngrams","keywords.e_ngrams^2"],"fuzziness": 1
}
}
}'
当我将其粘贴到terminal
中时,该命令将起作用,并将返回以下结果。
{
"took": 1,"timed_out": false,"_shards": {
"total": 1,"successful": 1,"skipped": 0,"Failed": 0
},"hits": {
"total": {
"value": 6,"relation": "eq"
},"max_score": 1.0,"hits": [
{
"_index": "stats","_type": "_doc","_id": "daily-covid-19-deaths","_score": 1.0,"_source": {
"title": "Daily Covid-19 Deaths"
}
}]
}
},
但是,当我通过角度进行呼叫时,不仅仅将title
返回为_source
,还会返回我所有其他参数,这也表明呼叫无法正常工作。
这是我到目前为止尝试过的。
const httpParams: HttpParams = new HttpParams();
httpParams.set('_source',JSON.stringify(['title','slug']));
httpParams.set(
'query',JSON.stringify({
multi_match: {
query: query,type: 'best_fields',fields: [
'title.e_ngrams^4','description.e_ngrams','keywords.e_ngrams^2',],fuzziness: 1,},})
);
this.http
.get(environment.ES.searchAPI,{
headers: this.httpHeaders,params: httpParams,})
.subscribe((data: any) => {
this.searchResults.next(this.parseResults(data));
});
}
这将返回结果给我,但是传递的参数(例如_source
)不起作用。它只是返回所有结果。
这是我的角度应用httpClient
从上面的代码返回的内容。
解决方法
您可以改用POST request
。
一个例子:
const body = JSON.stringify({
_source: ['title','slug'],query:{
multi_match: {
query: query,type: 'best_fields',fields: [
'title.e_ngrams^4','description.e_ngrams','keywords.e_ngrams^2',],fuzziness: 1,}
}
});
const httpHeaders = new HttpHeaders({
'Content-Type' : 'application/json'
});
this.httpClient.post(environment.ES.searchAPI,body,{
headers:httpHeaders
})
.subscribe((data: any) => {
console.log(data);
});
那么为什么在您的示例中却得到了所有结果参数?
您的GET request
忽略了params: httpParams
,因为httpParams
是null
。
尝试将httpParams.set
更改为httpParams = httpParams.set