错误:SyntaxError:在 fetch.then.response 处意外结束 JSON 输入

Ric*_*hes 5 javascript api post fetch

每次尝试在我的 API 中使用 POST 方法时,我都会收到此错误。

SyntaxError: Unexpected end of JSON input at fetch.then.response 
Run Code Online (Sandbox Code Playgroud)

当我使用 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))}
Run Code Online (Sandbox Code Playgroud)

有人能帮我吗?谢谢你。

编辑:我只是添加这一行来查看日志:

.then(response => console.log(response))
Run Code Online (Sandbox Code Playgroud)

这是我得到的:

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

Nin*_*liu 10

这意味着所获取的页面myURL/test不会以 JSON 内容或格式错误的 JSON 内容进行响应。这不是您的脚本中的错误,这很好,这是您的服务器的错误,未在 .json 处提供 JSON 内容myURL/test

另请注意,服务器可能不会对同一 URL 的 GET 请求和 POST 请求做出类似的响应!如果您从 GET 请求中获取有效 JSON,但如您所述,未能从 POST 请求中获取有效 JSON,则您的服务器可能正在根据请求类型提供不同的内容。调查那个。

调试提示

  • 更换then(resp => resp.json())then(resp => resp.text()).then(console.log),看看有什么提供的内容的样子
  • 使用 Postman 模拟 API 调用,查看所提供的内容是什么样的,以及更多细节
  • 使用开发人员工具检查响应:
    1. 在 Chrome 中
    2. 打开控制台 (F12)
    3. 转到network选项卡
    4. 单击文件服务器 myURL/test
    5. 单击response: 这将是文本内容。它应该是格式正确的 JSON。