0

I need to send an HTML string to the backend to be processed. To do this I am using Angular's HttpClient. However, the framework refuses to give me any meaningful error message other than a 400 response code. Below is my code.

Service method:

exportTestAsPdf(testHtml: string): Observable<any> {
    return this.http.post<any>(this.baseTestApiUrl + "Print", `\"${testHtml}\"`, this.requestHeaders);
}

requestHeaders:

protected get requestHeaders(): { headers: HttpHeaders | { [header: string]: string | string[]; } } {
  const headers = new HttpHeaders({
    Authorization: `Bearer ${this.authService.accessToken}`,
    'Content-Type': "application/json",
    Accept: "application/json, text/plain, */*"
  });

  return { headers };
}

ASP.NET endpoint:

[HttpPost]
public IActionResult Print([FromBody] string testHtml)
{
    // Code here
}

It doesn't give me 404 so I know the endpoint is found. What is the problem?

I followed the answers in this SO post but those did not help me.

M. Azyoksul
  • 1,580
  • 2
  • 16
  • 43
  • Maybe check logs in DevTools. It could be a CORS issue.`Console` or `Network` tab should provide you some meaningful error message. – Prabh Sep 25 '21 at 20:31
  • I am using this environment quite extensively so it is not a CORS issue. I will check the tabs you mentioned. – M. Azyoksul Sep 25 '21 at 20:33
  • I am assuming you are subscribing to `exportTestAsPdf` somewhere. `this.service.exportTestAsPdf('dd').subscribe({})` to generate API error – Prabh Sep 25 '21 at 20:36
  • @Prabh I am subscribing ofc. I didn't want to include unnecessary parts of the code. – M. Azyoksul Sep 25 '21 at 20:48

2 Answers2

1

Maybe use "${encodeURIComponent(testHtml)}" when posting your string

Ben Matela
  • 52
  • 4
1

Try to send the value like this.

  exportTestAsPdf(testHtml: string): Observable<any> {
  const body = { data : "Print" +  `\"${testHtml}\"`};
        return this.http.post<any>(this.baseTestApiUrl , body, {this.requestHeaders});
    }

In your backend, declare string data type named data.

Venkatesh K
  • 133
  • 1
  • 1
  • 11