【问题标题】:Angular 9 HttpErrorResponse 'JSON.Parse error' while response is OK响应正常时 Angular 9 HttpErrorResponse 'JSON.Parse error'
【发布时间】:2020-11-23 14:04:54
【问题描述】:

为什么会引发错误?

 deleteUser(userId: string) {
    this.dataService.deleteUser(userId).subscribe((response: string) => {
      console.log(response);
    });
  }

"SyntaxError: JSON 中位置 1 的意外标记 f 在 JSON.parse() 在 XMLHttpRequest.onLoad (https://localhost:5001/vendor.js:34968:51) 在 ZoneDelegate.invokeTask (https://localhost:5001/polyfills.js:412:35) 在 Object.onInvokeTask (https://localhost:5001/vendor.js:72879:33) 在 ZoneDelegate.invokeTask (https://localhost:5001/polyfills.js:411:40) 在 Zone.runTask (https://localhost:5001/polyfills.js:180:51) 在 ZoneTask.invokeTask [作为调用] (https://localhost:5001/polyfills.js:493:38) 在 invokeTask (https://localhost:5001/polyfills.js:1634:18) 在 XMLHttpRequest.globalZoneAwareCallback (https://localhost:5001/polyfills.js:1671:25)"

响应是纯字符串值,状态为 200。

我错过了什么?

【问题讨论】:

  • 你能把http请求返回的数据贴出来吗?
  • 你在前端使用JSON.Parse()吗?如果不是,错误可能源于后端的某个地方。
  • @user2263572 你可以在屏幕截图中看到它,在error body 有属性text
  • @MichaelD 不,我不是。如果后面返回字符串,后面会怎样?
  • @anatol:如果你能提供http://localhost:5001 中的后端是如何实现的,我会更好。尤其是/api/data/users/...端点的处理。

标签: json angular typescript angular-httpclient


【解决方案1】:

使用正确的 responseType 更新 dataService 中的 deleteUser 方法(默认为 JSON)。另外,我假设那是您使用 httpClient 的地方。

httpClient.get('your_endpoint', { responseType: 'text' }).subscribe(result => {
    console.log(result);
});

您返回的是文本,而不是 JSON。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 2020-11-04
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    相关资源
    最近更新 更多