react.js中的JSON输入意外结束

时间:2019-02-05 14:46:31

标签: javascript reactjs npm promise fetch

我得到

  

未处理的拒绝(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));
  }

我没有从数据库中获得该号码,但我不再收到错误

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

这里有一些小问题

  • 在您的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'))

答案 2 :(得分:1)

在查看服务器代码时,您似乎正在尝试从结果数组中返回第一个元素。返回此结果将导致发送回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)
}

希望这会有所帮助!