Angular 6: HttpErrorResponse SyntaxError: Unexpected token s in JSON

Angular 6: HttpErrorResponse SyntaxError: Unexpected token s in JSON

我正在发布一个请求,我想我会收到一个 'success' 字符串作为响应。我收到一个 HttpResponseError,其中包含下图中发布的以下信息。

采购订单服务

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

采购订单组件

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

我这样做的方式与文档中的方式相同。请指出我做错了什么。

这与您的 api 响应类型有关,success 无效 json 格式,默认情况下 HttpClient 应为 json 响应类型并尝试稍后解析它。您可以通过将响应类型设置为 text 来解决此问题

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

就像已经说过的,这与来自您的服务器的响应有关。

在我的例子中,我有一个 Spring 启动应用程序返回了这个:

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

这是我在 Angular 结束时得到的回应:

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

所以我所做的是在我的 Spring 引导应用程序中创建自定义 CustomHttpResponse class,然后将我的控制器中的代码更改为:

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

现在我明白了:

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

本质上,此错误发生在 Angular 期望 JSON 但得到其他东西时

我在获取 pdf 数据缓冲区作为响应时也遇到了同样的问题,我按照以下方式处理它,它对我有用

服务器端

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

在Angular服务中 下载PDF(日期范围,实验室){

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

} 在 Component.ts 文件中

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