javascript - 错误 : SyntaxError: Unexpected end of JSON input when using fetch()

标签 javascript json reactjs

我正在尝试在 Go API 服务器和基于 React 的前端之间发送 JSON。我收到以下错误:

错误:语法错误:JSON 输入意外结束

它说这是发生在第 25 行

.then(response => response.json())

这是相关函数:

postData() {
fetch('stuff/', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'Bob',
    age: 53,
  })
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}

在尝试一些故障排除后,我将错误捕获添加到带有“成功”和“错误”输出的函数中,这样它至少会停止弹出错误页面,并在 API 服务器上添加了一些控制台输出以查看数据是否正确正在通过。

除了发生错误外,一切似乎都按预期工作。 Go API 服务器正在接收 json 数据,我能够将其解码为结构并将数据写入控制台,这样我就知道数据正在传递。操作的 Go 端没有抛出任何错误。

我无法找出可能导致错误的原因?寻找有关如何进一步解决此问题或解决错误的一些建议。

更新: 正如 Dale 建议的那样,我已将 .then(response => console.log(response)) 放入我的代码中。我用这段代码替换了标准的 .then(response => response.json()) 。下面是来自 chrome 开发工具的控制台屏幕截图。

response output

另外值得注意的是,在这种情况下不会弹出错误代码。错误可能与服务器端代码有关吗?下面是 POST 端点的处理程序

func handlePostTest(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
    fmt.Print(err.Error())
}
var aPerson Person
json.Unmarshal(body, &aPerson)
fmt.Print(" ", aPerson.Name, " ", aPerson.Age)
}

最佳答案

从错误消息和 HTTP 响应中可以明显看出,如果您正在使用 fetch api 并从服务器端返回 HTTP 200,那么您应该发送一些内容,例如 "OK" ,否则返回空字符串如果您在响应顶部使用 .json() ,则会导致错误,因为它不是有效的 json。如果您没有发送任何内容,请从服务器端发送 HTTP 204(无内容)。

因此对于您的情况,您应该从服务器端发送一些内容。

关于javascript - 错误 : SyntaxError: Unexpected end of JSON input when using fetch(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49974346/

相关文章:

json - Groovy 中映射到字符串/字符串到映射的转换

javascript - 在 React 中渲染图像

javascript - Ember 数据 : Get a Model in the Console

javascript - 在 Phonegap 应用程序中打开 Google Play/Rate 应用程序

javascript - 在多个值后过滤

javascript - 最低有效 JSON 是多少?

Javascript - 如何检查 "certain"复选框而不是全部使用我当前的代码?

javascript - ubuntu 18.04- Ember : command not found

javascript - 动态设置Plotly.js表格组件的高度

javascript - React 高阶组件初始 Prop