【发布时间】:2021-01-17 06:09:52
【问题描述】:
每次我尝试在我的 API 中使用 POST 方法时都会收到此错误。
SyntaxError: Unexpected end of JSON input at fetch.then.response
当我使用 GET 方法时,我可以正常获取数据。 这是代码:
const teste = () => {
fetch("myURL/test", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
id: 1,
name: "Teste",
amount: 1,
value: 3
})
})
.then(response => response.json()) //Here is the error
.then(data => {
console.log(data);
})
.catch((err)=>console.log(err))}
有人可以帮助我吗?谢谢。
编辑: 我只是添加这一行来查看日志:
.then(response => console.log(response))
这是我得到的:
Response {
type: "cors",
url: "myURL/test",
redirected: false,
status: 201,
ok: true,
…}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 201
statusText: ""
type: "cors"
: "myURL/test"
__proto__: Response
【问题讨论】:
-
那么响应实际上是什么样的?
-
@Pointy 我刚刚收到此错误:SyntaxError: Unexpected end of JSON input at fetch.then.response
-
关于@pointy 的评论,您可以通过将
then(resp => resp.json())替换为then(resp => resp.text()).then(console.log)来查看回复的内容,并通过包含记录的文本来编辑您的回复 -
或者直接在浏览器开发者工具的“网络”标签中查看
-
@NinoFiliu 我照你说的做了。
标签: javascript api post fetch