gpt4 book ai didi

mysql - 如何以 React 形式管理来自 Express 的 mysql 查询错误?

转载 作者:行者123 更新时间:2023-11-29 15:55:55 26 4
gpt4 key购买 nike

我试图根据 Express 后端上的 SQL 查询是否成功将用户发送到两个不同的页面。但当我使用此代码时,仅显示成功路线。

我以前没有等待语句,但遇到了同样的问题。我不确定 react 端是否将错误消息作为响应,因为它仍在从后端登录到控制台。

这是提交表单时调用的前端方法:

        e.preventDefault();
console.log(this.state);
const newPost = {
pet_name : this.state.pet_name,
content : this.state.content,
content : this.state.content,
owner : 'testOwner',
email : 'test@gmail.com',
img_path : this.state.upload_image
};
//fetch instead of this to talk about in diss

try {
const postData = await axios.post('http://localhost:3306/reportpet', newPost)
.then(res=>console.log(res.data));
this.props.history.push('/postsubmitted')

} catch(error) {
console.log("Catch = ", error.response);
this.props.history.push('/posterror')

}```

The route on the backend is as follows:
```router.post('/reportpet', function (req, res) {

var pet_name = req.body.pet_name,
content = req.body.content,
date = req.body.date,
owner = req.body.owner,
email = req.body.email,
img_path = req.body.img_path;

const query = "INSERT INTO `posts` (`post_id`, `pet_name`, `content`, `date`, `owner`, `email`, `img_path`) VALUES (?, ?, ?, UTC_TIMESTAMP(),?, ?, ?);"
console.log(query);
connection.query(query, [pet_name, pet_name, content, owner, email, img_path ], function(err, result) {
(err)?res.send(err+'error was created'):res.json(result);
if (err) throw err;
console.log('rows inserted')
})

})

module.exports = router

当数据没有添加到数据库时,我希望用户被发送到错误组件。当成功时,我希望显示成功组件。

最佳答案

尝试在await中跳过使用.then()。并确保您的后端返回带有正确 HTTP 错误代码(4xx 或 5xx)的响应,以便 axios 知道发生了错误。

try {
const postData = await axios.post('http://localhost:3306/reportpet', newPost)

console.log(postData);

this.props.history.push('/postsubmitted')
} catch(error) {
console.log("Catch = ", error.response);
this.props.history.push('/posterror')
}

关于mysql - 如何以 React 形式管理来自 Express 的 mysql 查询错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56459779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com