【问题标题】:Unexpected end of JSON input in react.jsreact.js 中 JSON 输入的意外结束
【发布时间】:2019-06-29 10:08:24
【问题描述】:

我收到了

未处理的拒绝 (SyntaxError):JSON 输入意外结束

按提交时出错。

这是我的代码:

onButtonSubmit = () => {
this.setState({imageUrl: this.state.input})
app.models
  .predict(
    Clarifai.FACE_DETECT_MODEL, 
    this.state.input)
  .then(response => {
    if (response) {
      fetch('http://localhost:3000/image', {
          method: 'put',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({
            id: this.state.user.id
        })
      }).then((response) => response.json())
        .then((count) => {
          this.setState(Object.assign(this.state.user, {entries: count}));
        })
  }
    this.displayFaceBox(this.calculateFaceLocation(response))
  })
.catch(err => console.log(err));

}

My app.js

我是 React.js 的新手,我想了解更多信息,但我不知道为什么会出现此错误,并且由于数据库已更新,它会出现。当我再次登录时,页面也会更新。

我得到的错误

    Unhandled Rejection (SyntaxError): Unexpected end of JSON input
(anonymous function)
C:/Users/cmham/Projekter/facedetector/src/App.js:94
  91 |     body: JSON.stringify({
  92 |       id: this.state.user.id
  93 |   })
> 94 | }).then((response) => response.json())
     | ^  95 |   .then((count) => {
  96 |     this.setState(Object.assign(this.state.user, {entries: count}));
  97 |   })
View compiled

我该如何解决这个问题?

编辑我的服务器部分

app.put('/image', (req, res) => {
  const { id } = req.body;
  db('users').where('id', '=', id)
    .increment('entries', 1)
    .returning('entries')
    .then(entries => {
      res.json(entries[0]);
    })
    .catch(err => res.status(400).json('unable to get entries'))
})

编辑 2 现在我从服务器收到一个 1,但我需要的是数据库中的更新数字。

这是我现在的服务器:

app.put('/image', (req, res) => {
  const { id } = req.body;
  db('users').where('id', '=', id)
    .increment('entries')
    .returning('entries')
    .then(entries => {
      res.json(entries);

})
  .catch(err => res.status(400).json('unable to get entries'))
})

这是我的 App.js:

onButtonSubmit = () => {
this.setState({imageUrl: this.state.input})
app.models
  .predict(
    Clarifai.FACE_DETECT_MODEL, 
    this.state.input)
  .then(response => {
    if (response) {
      fetch('http://localhost:3000/image', {
          method: 'put',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({
            id: this.state.user.id
        })
      }).then((response) => response.json())
        .then((count) => {
           console.log(count)
          this.setState({
            ...this.state.user, entries: count++

          });
        })
        .catch(error => console.log('An error occured ', error))
  }
    this.displayFaceBox(this.calculateFaceLocation(response))
  })
.catch(err => console.log(err));
  }

我没有从数据库中获取号码,但我不再收到错误提示

【问题讨论】:

  • 请发布服务器的答案。可能缺少标题。
  • @RandyCasburn 是一个对象 {id:this.state.user.id}
  • 您确定您确实成功地取回了用户数据吗?在您进行获取以确保之前,控制台记录您的 this.state.user.id。
  • entries 中到底是什么?你能发布来自服务器的 json 响应吗?
  • 如果服务器响应为空,.then() 将执行,但在(response) => response.json() 这一行失败。

标签: javascript reactjs npm promise fetch


【解决方案1】:

我认为您需要先解析 req.body,然后再将其提取到 const id 并在您的数据库查询中使用它

const { id } = JSON.parse(req.body);

【讨论】:

  • 我确实在我的数据库查询中使用它并解析它只是给了我一个错误SyntaxError: Unexpected token o in JSON at position 1
  • 将 res.json() 替换为 res.send(JSON.stringify(entries[0])
  • 现在我得到了一个PUT http://localhost:3000/image 500 (Internal Server Error) An error occured SyntaxError: Unexpected token < in JSON at position 0 at App.js:95@Roy.B
  • @TWOcvfan 有什么反应?你能在 response.json() 之前 console.log 响应吗
  • @TWOcvfan 我的猜测是来自 db 的响应包含 html 标签 JSON.parse('<... content-type:application>
【解决方案2】:

这里有一些小问题

  • 在您的 this.setState(Object.assign(this.state.user, {entries: count})) 中,我了解您在此处尝试执行的操作,但不确定您是否希望这样做。
  • 另外,您没有完全正确地处理您的承诺

记录 count 的值也会有所帮助(您可能没有获得预期的值

app.models
  .predict(
    Clarifai.FACE_DETECT_MODEL, 
    this.state.input)
  .then(response => {
    if (response) {
      fetch('http://localhost:3000/image', {
          method: 'put',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({
            id: this.state.user.id
        })
      }).then((response) => response.json())
        .then((count) => {
          this.setState({
             user: Object.assign(this.state.user, {entries: count}) 
// Notice the difference here 
          });
        })
        .catch(error => console.log('An error occured ', error))
  }
    this.displayFaceBox(this.calculateFaceLocation(response))
  })
.catch(err => console.log(err));

另外,对 knex 不是很熟悉,但您可能想要更改

app.put('/image', (req, res) => {
  const { id } = req.body;
  db('users').where('id', '=', id)
    .increment('entries')
    .returning('entries')
    .then(entries => {
      res.json(entries);

})
  .catch(err => res.status(400).json('unable to get entries'))
})

类似于:

app.put('/image', (req, res) => {
  const { id } = req.body;

  db('users').where('id', '=', id)
    .increment('entries', 1)
    .then(()=> 
      db('users').where('id', '=', id).then(user => res.json(user[0].entries))
    )
    .catch(err => res.status(400).json('unable to get entries'))
})

在你的server.js

我怀疑你也可以做类似的事情(我以前没有使用过 knex,但是在 SequelizeJS 中可以做到这样的事情):

db('users').where({id}).then(user => 
  user[0].increment('entries', 1).then(() => res.json(user[0].entries))
).catch(err => res.status(400).json('unable to get entries'))

【讨论】:

  • 你得到@TWOcvfan 的错误是什么?另外,我也可以看看你的完整后端代码吗?
  • 更新了答案,看看@TWOcvfan
  • 它消除了错误,但现在服务器只发回 1 @delis
  • 那么你对服务器@TWOcvfan 有什么期望
  • 我期待新的条目数量,以便可以在@delis 网站上更新
【解决方案3】:

查看您的服务器代码,您似乎正试图从结果数组中返回第一个元素。返回 this 会导致返回一个 JSON 对象:

.then(entries => {
  res.json(entries[0]);
})

不过,您的前端代码似乎只在等待计数:

.then((response) => response.json())
.then((count) => { ... })

我不完全确定这是否是您想要实现的目标,但将条目计数发送回 JSON 对象应该可以在后端解决问题。另请注意将错误作为catch 块中的对象发回:

db('users').where('id', '=', id)
  .increment('entries', 1)
  .returning('entries')
  .then(entries => {
    res.json({ count: entries.length });
  })
  .catch(err => {
    res.status(400)
       .json({ message: 'unable to get entries' })
  })

前端代码也需要一些修改(参见第二个then() 并添加了catch 块)。我也鼓励使用 the object spread syntax 而不是 Object.assign(),因为它更容易阅读和掌握:

fetch('http://localhost:3000/image', {
  method: 'put',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    id: this.state.user.id
  })
})
.then((response) => response.json())
.then(({ count }) => {
  this.setState({
    user: {
      ...this.state.user, 
      entries: count,
  });
})
.catch(({ message })=> {
  alert(message)
}

希望这会有所帮助!

【讨论】:

  • 我的服务器响应现在只是{} 并且页面没有更新@chrisg86
猜你喜欢
  • 1970-01-01
  • 2020-07-10
  • 2015-08-05
  • 2021-07-03
  • 2017-12-15
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
相关资源
最近更新 更多