Angular HttpClient Get method with body

Bruno Miguel picture Bruno Miguel · Jan 12, 2019 · Viewed 46.6k times · Source

I'm improving an existing API, and the requirement is to provide a single get method which can accept multiple search criteria and based on those criteria perform the query.

I'm using Spring MVC. The get method signature:

@GetMapping("/subscribers")
public ResponseEntity<List<SubscriberDTO>> getAllSubscribers(Pageable pageable, @RequestBody List<SearchCriteria> lstSearchCriteria)

The implementation is working as expected tested on Postman

Now I was going to Angular to implementing the front end and I can't find a way to send a body through HttpClient Get method...

I'm kind of stuck. Should I send the search criteria over headers? Or there's a better way of doing it?

Answer

Nuno Sousa picture Nuno Sousa · Jan 12, 2019

As far as I can tell you cannot use HttpClient get to send a body. You could use the query at least for it to be idiomatic. (Or you can try to force the issue somehow).

Lets say you have an array with your criteria:

const criteria = [ {a: 25}, {b: 23} ];
http.get(url + '/?criteria='+ encodeURIComponent( JSON.stringify(criteria)));

Sending a body in a GET request is a violation of some RFC standard, and even though it might work you're bound to summon some arcane demons.