Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular HttpClient Get method with body

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?

like image 521
Bruno Miguel Avatar asked Jan 12 '19 21:01

Bruno Miguel


People also ask

Can we send request body in GET request in Angular?

Just to clarify some of the answers here, firstly, as stated Angular does not support supplying a body with a GET request, and there is no way around this. The reason for that is not Angular's fault but that of XMLHttpRequest (XHR), the API that browsers use for making requests.

What is the use of HttpClient get () method?

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.

Does HTTP GET have a body?

Yes. In other words, any HTTP request message is allowed to contain a message body, and thus must parse messages with that in mind. Server semantics for GET, however, are restricted such that a body, if any, has no semantic meaning to the request.

Can we send body GET request?

No, We cannot send Body with GET Method. The Purpose of GET is to retrieve data. If i take example of database then the select query is a kind of GET. But if you want to pass some values through GET method then you can do that by passing the input as a query param.


1 Answers

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.

like image 181
Nuno Sousa Avatar answered Oct 03 '22 10:10

Nuno Sousa