Angular 6:HttpErrorResponse SyntaxError:JSON中的意外标记

use*_*188 9 rest xmlhttprequest httpresponse typescript angular

我发布了一个请求,我想收到一个'成功'字符串作为响应.我收到一个HttpResponseError,下面的图片中显示了以下信息.

在此输入图像描述

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'))
                 );
  }
Run Code Online (Sandbox Code Playgroud)

PurchaseOrderComponent

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

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

当我实现@Muhammed提供的答案时显示的错误

mal*_*awi 13

这与您的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')));
Run Code Online (Sandbox Code Playgroud)

  • 这就是我所做的`{headers:this.header,responseType:'text'as'json'})`.只是添加文字对我没用.从Github的讨论中,人们补充说要让它发挥作用 (5认同)
  • 我不得不添加为“json”。在它起作用之前,如果您可以编辑答案,那么我接受它。{headers: this.header , responseType:'text' as 'json'}) (2认同)