ThomasFromUganda
ThomasFromUganda

Reputation: 410

HTTP post request keeps sending an empty body

I am sending a post request to my server and from the server side, I only get an empty body.

My client is with angular.

Here is the code for the service that sends the request:

public constructor(private http: HttpClient) { }

  public addImagePair(gameName: string, originalImage: File, modifiedImage: File): Observable<ICommonImagePair> {
    const formData: FormData = new FormData();
    formData.append("name", gameName);
    formData.append("originalImage", originalImage);
    formData.append("modifiedImage", modifiedImage);

    new Response(formData).text().then(console.log);
    return this.http.post<ICommonImagePair>(this.BASE_URL + "image-pair", formData);
  }

  public addGameCard(gameName: string, imagePairId: string, pov: POVType): Observable<ICommonGameCard> {
    const formData: FormData = new FormData();
    formData.append("name", gameName);
    formData.append("image-pair-id", imagePairId);
    formData.append("pov", "Simple");

    new Response(formData).text().then(console.log);
    return this.http.post<ICommonGameCard>(this.BASE_URL + "gamecard", formData);
  }

Here is the code for the component that calls the service:

public addImagePair(): void {
    this.simplePOVGameGeneratorService.addImagePair(this.gameName, this.originalImageFile, this.modifiedImageFile)
      .subscribe((imagePair: ICommonImagePair) => {
        this.simplePOVGameGeneratorService.addGameCard(imagePair.name, imagePair.id, POVType.Simple)
          .subscribe((gameCard: ICommonGameCard) => {
            console.log(gameCard);
          });
      });
  }

In my component, I first make a request for addImagePair(), which does send a request without any issues. Then, I call addGameCard() with almost the same code and somehow the body is empty. I console log before making the request to make sure there is actually data. I also console log on the server and the body is empty. What the hell could cause this?

Upvotes: 1

Views: 809

Answers (1)

Niladri
Niladri

Reputation: 5962

You can use the flatMap operator instead of manually subscribing to nested observables like below -

public addImagePair(): void {
    this.simplePOVGameGeneratorService.addImagePair(this.gameName, this.originalImageFile, this.modifiedImageFile)
      .flatMap((imagePair: ICommonImagePair) => this.simplePOVGameGeneratorService.addGameCard(imagePair.name, imagePair.id, POVType.Simple))
       .subscribe((gameCard: ICommonGameCard) => {
            console.log(gameCard);
          });
      });
  }

You can also pass the data in the post method as string literal instead of FormData like formdata = { "name":gameName,"image-pair-id":imagePairId,"pov": "Simple"} and then use return this.http.post<ICommonImagePair>(this.BASE_URL + "image-pair", JSON.stringify(formData)); in the addGameCard method.

Upvotes: 1

Related Questions