[英]Unexpected end of JSON input in react.js
I'm getting an我得到一个
Unhandled Rejection (SyntaxError): Unexpected end of JSON input
未处理的拒绝 (SyntaxError):JSON 输入的意外结束
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));
} }
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.我是 React.js 的新手,我想了解更多信息,但我不知道为什么会出现此错误,并且由于数据库已更新,因此它通过了。 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.编辑 2现在我从服务器收到一个 1,但我需要的是数据库中更新的数字。
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:这是我的 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我没有从数据库中获取号码,但我不再收到错误消息
我认为您需要先解析req.body,然后再将其提取为const id并在数据库查询中使用它
const { id } = JSON.parse(req.body);
There are a number of minor issues here 这里有一些小问题
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. this.setState(Object.assign(this.state.user, {entries: count}))
,我了解您在此处尝试执行的操作,但不确定这是您要执行的操作。 logging the value of count
would also help though (it's possible you are not getting the value you expect 记录
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));
Also, not very familiar with knex but you may want to change 另外,对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'))
})
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
在您的
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): 我怀疑您也许也可以做类似的事情(我以前没有使用过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'))
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:
返回此结果将导致发送回JSON对象:
.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. 我不完全确定这是否是您要实现的目标,但是将条目计数发送回JSON对象应该可以解决后端问题。 Also note sending back the error as an object in the
catch
block: 另请注意,将错误作为
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' })
})
Frontend code also needs some modifications (see the second then()
and added catch
block). 前端代码也需要进行一些修改(请参阅第二个
then()
和添加的catch
块)。 I would also encourage using the object spread syntax instead of Object.assign()
as it's easier to read and grasp: 我也鼓励使用对象传播语法而不是
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)
}
Hope this helps! 希望这可以帮助!
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})}
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.
希望你能解决你的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.