【发布时间】: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));
}
我是 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