Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6: HttpErrorResponse SyntaxError: Unexpected token s in JSON

I am posting a request and I am suppose to receive a 'success' string back as response. I am getting an HttpResponseError with the following information posted in the image below.

enter image description here

PurchaseOrderService

postPurchaseOrderCustom(purchaseOrderCustom: PurchaseOrderSaveCustom) {
 const url = `${this.localUrl}purchaseOrderCustom`;
 return this.http.post<String>(url, purchaseOrderCustom, {headers: this.header})
            .pipe(
                   catchError(this.handleError('postPurchaseOrderCustom', 'I am an error'))
                 );
  }

PurchaseOrderComponent

this.purchaseOrderService.postPurchaseOrderCustom(purchaseOrderCustom).subscribe( response => {
  console.log("Testing", response);
  },
  error => {
    console.error('errorMsg',error );   
  }

The way I am doing it is the same way its done in the documentation. Do point out to me what I am doing wrong.

error shown when I implement answer provided by @Muhammed

like image 859
user3701188 Avatar asked Jul 29 '18 19:07

user3701188


3 Answers

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 image 98
Muhammed Albarmavi Avatar answered Nov 20 '22 19:11

Muhammed Albarmavi


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

like image 28
Ojonugwa Jude Ochalifu Avatar answered Nov 20 '22 17:11

Ojonugwa Jude Ochalifu


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);
 }
like image 1
Rakesh Pandey Avatar answered Nov 20 '22 17:11

Rakesh Pandey