簡體   English   中英

react.js 中的 JSON 輸入意外結束

[英]Unexpected end of JSON input in react.js

我得到一個

未處理的拒絕 (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));

}

我的 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));
  }

我沒有從數據庫中獲取號碼,但我不再收到錯誤消息

我認為您需要先解析req.body,然后再將其提取為const id並在數據庫查詢中使用它

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

這里有一些小問題

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

查看服務器代碼,您似乎正在嘗試從結果數組中返回第一個元素。 返回此結果將導致發送回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塊)。 我也鼓勵使用對象傳播語法而不是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)
}

希望這可以幫助!

這可能發生在您的服務器接收數據名稱和您的客戶端發送名稱不同的情況下。 like (//in server ( req.body.userName ) & //in client (fetch....{body:json.stringfy({ username : user.username //from your state})}

看星標,這個用戶名不相等。 希望你能解決你的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM