首页 > 解决方案 > Angular 6: HttpErrorResponse SyntaxError: Unexpected token s in JSON

问题描述

我正在发布一个请求,并且我想收到一个“成功”字符串作为响应。我收到一个 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 );   
  }

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

当我执行@Muhammed 提供的答案时显示错误

标签: angularresttypescriptxmlhttprequesthttpresponse

解决方案


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

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

推荐阅读