【问题标题】:Error: SyntaxError: Unexpected end of JSON input at fetch.then.response错误:SyntaxError:在 fetch.then.response 处 JSON 输入意外结束
【发布时间】: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


【解决方案1】:

这意味着在myURL/test 获取的页面没有响应 JSON 内容或格式错误的 JSON 内容。这不是您的脚本中的错误,这很好,这是您的服务器的错误,即未在 myURL/test 提供 JSON 内容。

另外,请注意,服务器可能不会对同一 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。

【讨论】:

  • 浏览器开发者工具会显示HTTP请求和响应的完整文本。
  • 确实!我将编辑我的答案以包含此内容。作为初学者,我从来没有真正使用过开发人员工具,所以我只想建议纯脚本提示。
  • @NinoFiliu 当我使用方法 GET 这是我得到的: [ { "id": 1, "name": "Coca-cola", "amount": 1, "value": 2.5 } ]
  • 尝试发布正文:{ data:{ I'd:1, name:"test#"}}
  • @RicardoSanches 您使用 POST 获取但仅使用 GET 获取有效 JSON,因此您的服务器根据 POST/GET 提供不同的内容。请参阅我的答案中添加的段落。
【解决方案2】:

基本上 GET 方法不会将您的主体对象发送到您获得响应的服务器。只有 POST 操作会将您的 body 对象发送到服务器。

我假设您要发送的对象是问题所在。您尝试连接的服务器不希望正文对象为字符串,或者您应确保在处理之前已正确解析 JSON。

【讨论】:

  • 我认为你是对的。我正在使用 SwaggerHub 创建 API,我认为这可能是问题所在。
【解决方案3】:

看起来您正在调用的 API 在此特定 POST 上没有响应正文。然后,当您调用 response.json()(将 response.body 转换为 json)时,它会出错。 或者响应是 body is not a valid json body。

如果你想以更时尚的方式处理这个错误,你可以这样:

tryGetJson = async (resp) => {
    return new Promise((resolve) => {
      if (resp) {
        resp.json().then(json => resolve(json)).catch(() => resolve(null))
      } else {
        resolve(null)
      }
    })
  }

https://github.com/github/fetch/issues/268#issuecomment-399497478

【讨论】:

    【解决方案4】:

    (对于迟到但正在处理这个问题的人)

    问题很可能是服务器错误或无效 URL,但您看不到它,因为互联网上所有如何使用 fetch 的示例都缺少一个重要部分 - 服务器或网络故障。

    我认为处理fetch 的正确方法是在转换为json 之前测试响应是否包含错误。

    在测试it.ok 的示例中检查第一个then 的部分:

    async function fetchData() {
        return await fetch('https://your-server.com/some-NOt-existing-url/')
            .then(it => {
                if (!it.ok) {
                    throw `Server error: [${it.status}] [${it.statusText}] [${it.url}]`;
                }
                return it.json();
            })
            .then(receivedJson => {
                // your code with json here...
            })
            .catch(err => {
                console.debug("Error in fetch", err);
                setErrors(err)
            });
    }
    

    (注意:it 只是从 Kotlin 借来的命名约定,它使 JavaScript 代码更短。它是表达式左侧任何内容的别名,因此在本例中为 response

    【讨论】:

      猜你喜欢
      • 2015-08-05
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 2020-03-09
      • 2019-12-27
      • 1970-01-01
      相关资源
      最近更新 更多