Search code examples
angulartypescriptangular-httpclient

Change response type for http.post


I have a post method using Angular's HttpClient.

I'm trying to subscribe to the response so I can do a few things after but I'm getting this error:

Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"XXXXXXX","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for XXXXXXXX","error":{"error":{},"text":"OK"}}

I've seen somewhere that this could be because it's not a valid JSON response, when I test it on Postman, I get a OK but not as JSON.

My question is, how do I work around this? Is there a way for me to convert this to JSON?

My method looks like:

submitInfo() {
   this.http.post(url, data).toPromise()
      .then(
          (response: Response) => {
              console.log(response);
          }
      ));
}

Solution

  • By default Angular tries to process HTTP responses as JSON and hence it tends to go into error handler even though the actual HTTP request succeeds. For non-JSON responses you can explicitly specify that you are expecting a text response in your HTTP request or to get the benefits of inbuilt Angular error handling for responses modify your response from server/middleware as a JSON.

    For non-JSON response try modifying your HTTP request like below

    this.http.post(url, parameters, { responseType: 'text' });