Angular 6: HttpErrorResponse SyntaxError: Unexpected token s in JSON

This related to your api respond type ,success is not valid json format,by default HttpClient is expected json response type and try to parse it later . You can solve this by set the respond type to text like this

return this.http.post<String>(
    url,
    purchaseOrderCustom,
    { headers: this.header, responseType: 'text' }
)
    .pipe(
        catchError(this.handleError('postPurchaseOrderCustom', 'I am an error')
        ));

Like it has already been said, this has everything to do with the response coming from your server.

In my case, I had a Spring Boot application that returned this:

return new ResponseEntity<>("Your SSN was generated successfully", HttpStatus.OK);

and this was the response I was getting on the Angular end:

{error: SyntaxError: Unexpected token Y in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHtt…, text: "Your SSN was registered successfully."}

So what I did was create a custom CustomHttpResponse class in my Spring Boot application and then changed the code in my controller to this:

        ...
        CustomHttpResponse customHttpResponse = new CustomHttpResponse();
        customHttpResponse.setMessage("Your SSN was registered successfully.");
        customHttpResponse.setStatus(HttpStatus.OK.value());

        return new ResponseEntity<>(new Gson().toJson(customHttpResponse), 
                                          HttpStatus.OK);
        }

Now I'm getting this:

{message: "Your SSN was registered successfully.", status: 200}
   message: "Your SSN was registered successfully."
       status: 200

Essentially, this error occurs when Angular is expecting JSON but gets something else instead


I was also facing same issue while getting pdf data buffer in response and I handled it in following manner, it's working for me

server side

pdf.create(output, options).toBuffer((err: any, buffer: any) => {
            if (err) reject(err);
           response.type('pdf');
response.send(buffer);
        });

in Angular Service downloadPdf(dateRange, labs){

return this.httpClient.post(url, data,{responseType:'blob'});

} And in Component.ts file

downPdf1(){
    this.analyticService.downloadPdf(this.dateRange, this.labs).subscribe(
      res => this.extractPdf(res),
      (error:any) => throwError (error || 'Server error')
  );
  }

 extractPdf(res){
     let myBlob: Blob = new Blob([res], {type: 'application/pdf'}); 
     var fileURL = URL.createObjectURL(myBlob);
     window.open(fileURL);
 }