Angular 6: HttpErrorResponse SyntaxError: Unexpect

2020-03-12 05:01发布

问题:

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.

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.

回答1:

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')));


回答2:

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



回答3:

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);
 }