Search code examples
phpangularhttpclientpostmanangular7

How to send the "body" parameter to HttpClient.get ()?


I have an "api rest" that I created in PHP, the service returns a JSON with the parameters of "header", "body", "get", "pos", which comes to receive without any type of validation. Now I have created a service in angular to connect with the "api rest", all right up there, the problem I have is that I want to send a parameter as a "BODY", but I do not know how, I have been investigating but I have not found a shape. Is it possible to send the "body" via HttpClient.get()?

to test my service use "postman".

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ServicioService {
  constructor(private http: HttpClient) { }
  getQuery(query: string){
    const url = `http://localhost:8080/servicio/`;

    const headers = new HttpHeaders({
      'Authorization': 'Bearer BQAiaibx-we0RSlZFN29B5TPF4t6egxbuuEsc5ZYZhpamHUhImd5'
    });
    const params = new HttpParams()
    .set('page', '2')
    .append('page', '3')
    .set('sort', 'abc');
    return this.http.get (url, { params, headers});
  }
  getNewReleases(){
    return this.getQuery("")
                .pipe( map((data: any) => {
                  return data;
                }));

  }
}

this is what the console prints when executing the code.


Solution

  • A GET request does not have a body. You should use POST or PUT.

    You can read here a little bit about the http methods. About the GET: The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect

    So, it would be wrong to send a body because a GET method should not change anything.