angular http get 在请求中将正文参数发送为 json

angular http get send body params as json in request

我正在尝试在 angular 中提出此请求:

curl --location --request GET 'http://localhost:5000/location/searchDistanceAndTags?pageNo=1&size=1' \
--header 'token: $IKFASOmV#*+JIL4X0FGTDZNRPB3GN7HvAB9QD2X8QWeLsqtKW1U5YHnxCMRywEbUZlu??oz!!!!6r' \
--header 'Content-Type: application/json' \
--data-raw '{
"lat": "38.8993487",
"lng": "-77.0145665",
"radius": "100",
"tags": ["bier"]
}'

这是我在 angular 中的代码,不幸的是没有设置参数(后端在 req.body 中没有收到任何数据)

 const dataset = {
  lat: '38.8993487',
  lng: '-77.0145665',
  radius: '100',
  tags: ['bier']
};

return this._httpClient.get<any>(`http://localhost:5000/location/searchDistanceAndTags?pageNo=${this.pageNumber}&size=10`, {
  headers: {token: this.apikey,
    'Content-Type':  'application/json'},
  params: dataset
});

Params可以通过HttpParams发送:

const params = new HttpParams()
   .set('lat', 'one!')
   .set('lng', "two");  // and so on

headers 可以通过以下方式创建:

const headers = new HttpHeaders()
        .set("X-CustomHeader", "custom header value");

this.httpClient.get<any>(yoururl,{params}) // {params} short form of {params:params}
or:
this.httpClient.get<any>(yoururl,{headers: headers, params: params})

尽管 GET 请求在技术上可以有一个如此 SO answer 中所示的主体,但实际上支持它的库并不多。正如您所指出的,CURL 确实如此。但是,前端 API 像 fetch,Xhr (XmlHttpRequest) 不允许在 GET 请求中发送正文。

Angular 的 HttpClient 如果我没记错的话使用 Xhr,所以你不能这样做。

您可以修改 API 以接受 post 请求,或者接受查询字符串中的参数