0

I'm getting an

Unhandled Rejection (SyntaxError): Unexpected end of JSON input

error when I press submit.

this is my code:

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

I new to React.js and I want to learn more, but I can't figure out why I get this error, and it goes through because the database gets updated. And when I login again, the page is also updated.

the error I get

    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

how do I resolve this?

Edit my server part

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'))
})

Edit 2 Now I receive a 1 from the server but what I need is the updated number from the database.

this is my server now:

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'))
})

and this is my 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));
  }

I don't get the number from the database, but I no longer get an error

7
  • Please post the answer of the server. There might be a header missing. Commented Feb 5, 2019 at 14:49
  • @RandyCasburn that is an object {id:this.state.user.id} . Commented Feb 5, 2019 at 14:54
  • are you sure you are actually getting the user data back successfully? console.log your this.state.user.id just before you make your fetch to make sure. Commented Feb 5, 2019 at 15:11
  • 2
    What exactly is in entries? Can you post the json response from the server? Commented Feb 5, 2019 at 15:14
  • 1
    If the server response is empty,.then() will execute, but fail on this line (response) => response.json(). Commented Feb 5, 2019 at 16:12

4 Answers 4

2

I think you need to parse the req.body before extracting it to const id and using it on your DB query

const { id } = JSON.parse(req.body);
Sign up to request clarification or add additional context in comments.

6 Comments

I do use it in my db query and parsing it just gave me an error SyntaxError: Unexpected token o in JSON at position 1
replace res.json() with res.send(JSON.stringify(entries[0])
now i get a 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 what is the response? Can you console.log response before the response.json()
@TWOcvfan my guess is that the response from db containing html tags JSON.parse('<...'). Its trying to parse it because of the header Content-Type:application/json,
|
1

There are a number of minor issues here

  • In your this.setState(Object.assign(this.state.user, {entries: count})), I understand what you are trying to do here but not sure this is how you want to do it.
  • Also you aren't fully handling your promise properly

logging the value of count would also help though (it's possible you are not getting the value you expect

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));

Also, not very familiar with knex but you may want to change

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'))
})

to something like:

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'))
})

in your server.js

I suspect you may also be able to do something like (I've not used knex before but something like this is doable in 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'))

7 Comments

What's the error you get @TWOcvfan ? Plus can I see your full backend code as well?
Updated the answer, take a look @TWOcvfan
It removed the error, but now the server just sends a 1 back @delis
So what value do you expect from the server @TWOcvfan
I expecting the new number of entries so it can be updated on the website @delis
|
1

Looking at your server code, it seems that you are trying to return the first element from the result array. Returning this would result in a JSON object being sent back:

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

Your frontend code, though, seems to wait for a count and nothing else:

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

I'm not entirely sure if that's what you want to achieve, but sending the entry count back in a JSON object should do the trick on the backend side. Also note sending back the error as an object in the catch block:

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' })
  })

Frontend code also needs some modifications (see the second then() and added catch block). I would also encourage using the object spread syntax instead of Object.assign() as it's easier to read and grasp:

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)
}

Hope this helps!

1 Comment

my response from the server is now just {} and the page doesn't update @chrisg86
0

this may happen for your server receiving data name and your client sending name is not same. like (//in server (req.body.userName) & //in client (fetch....{body:json.stringfy({username : user.username//from your state})}

look at the star marks, this user name are not equal. hope you could solve your problem.

1 Comment

Hey there. On Stackoverflow it's disencouraged to answer old posts (this one is from 2019) and has been solved. Answering old posts causes them to get "bumped" and become relevant again, which is not what we want of course. If you like someone's answer that's much more beneficial.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.