Girbouillle
Girbouillle

Reputation: 73

Angular 8 and spring boot api, Required request body is missing

I have a little issue. When i send a request to my api with Postman, it works, but when i send something with angular he doesn't like.

Postman : the request

Happy Spring :

@GetMapping("/searchs")
@CrossOrigin(origins = "http://localhost:4200")
public Collection<SearchFeedDTO> getFeed ( @RequestBody String data){
    System.out.println(data);
    System.out.println("I'm here");
    return null;
}

server response

Angular code:

// data = {test:"hello"};
getFeed(data):Observable<boolean>{

   return this.http.get<Answer>(`${this.baseUrl}api/searchs/`,data).pipe(
        map(res=>true),
        catchError(err=>{
            console.error(err);
            return of (false);
      })
   );
}

Sad Spring response : "required request body is missing"

And Angular isnt happy when i'm trying this.

return this.http.get<Answer>(`${this.baseUrl}api/searchs/`,{test:"test"}).pipe(

=> error "No overload matches this call".

Any idea?

Thanks a lot!

Upvotes: 0

Views: 1692

Answers (3)

Barremian
Barremian

Reputation: 31115

HttpClient does not support sending body in GET request. Based on @vicb's comment here:

IIRC the RFC does not prevent GET request from having a body but in practice most servers do not support this.

From GET specification:

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

So you either need to send the request as POST or send the data as query parameters. For multiple data, you could contain the data in an object and send a stringified version as a query parameter.

const test = {test: "test"};
return this.http.get(`${this.baseUrl}api/searchs/?test=` + encodeURIComponent(JSON.stringify(test));

And use the test variable in the backend.

Upvotes: 1

Shirantha Madusanka
Shirantha Madusanka

Reputation: 1695

To complete HTTP request you should implement the subscriber because you are creating the request using Observable.

Upvotes: 0

Reza
Reza

Reputation: 19883

Usually Get request should not have body so angular httpclient.get also don't accept body, either you need to send data to GET via query parameters

or change your backend to POST and then use the body. If your body is only text (not json), also you need to add correct headers to angular request

Upvotes: 0

Related Questions