angular http get send body params as json in request

Viewed 9342

i' m trying to make this request in 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"]
}'

here is my code in angular, unfortunately the params are not set (backend doesnt receive any data in 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
});
2 Answers

Even though GET request can technically have a body like indicated in this SO answer, not many libraries actually support it. CURL does, as you've indicated. However, front end APIs like fetch, Xhr (XmlHttpRequest) will not allow to send a body in a GET request.

Angular's HttpClient uses Xhr if I'm not mistaken, and so you won't be allowed to do this.

You can either modify your API to accept a post request instead, or accept the parameters in the query string

Params can be sent via HttpParams:

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

headers can be created via:

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

and

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