首页 > 解决方案 > Angular (8) Http.post() 给出 SyntaxError: Unexpected token O in JSON at JSON.parse 的位置 0

问题描述

当我尝试将数据发布到我的服务器时,我收到了错误:

SyntaxError: Unexpected token O in JSON at position 0 at JSON.parse...

我没有使用 JSON.parse() 所以我假设 Angulars Http.post() 自动执行此操作?

当我尝试 console.log(JSON.parse(data)) 时,我得到:

SyntaxError: Unexpected token o in JSON at position 1...

当我从 Postman 发送数据时 - 工作得很好,没有错误并且服务器接收到它。

当我在 fetch() api 请求中发送数据时 - 也可以正常工作,没有任何错误。

因此,这只发生在我尝试使用 angulars HTTP lib 并尝试发布时。下面是我发送的一些 JSON 数据的示例和我的 http 帖子的示例。

提前致谢!这一直让我发疯!

{"tutorialName":"cvbcvbxcvbxcvbbxcv","sections":[]}
this.http.post("http://127.0.0.1:5000/endpoint", JSON.stringify(this.tutorialForm.value)).subscribe();

标签: jsonangular

解决方案


原来解决方案是 Angular 中 HTTP.post 上的响应类型选项,它与服务器不一致(https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType类型)并默认为 JSON。感谢所有回答的人!


推荐阅读