我该如何从React形式的Express中管理mysql查询错误?

时间:2019-06-05 11:40:35

标签: mysql reactjs express

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

我以前没有await语句,但是有同样的问题。我不确定反应端是否正在接受错误消息作为响应,因为它仍从后端登录到控制台。

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

        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

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

2 个答案:

答案 0 :(得分:0)

尝试在等待中跳过使用.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')
}

答案 1 :(得分:0)

Mykola Prymak回答了这个问题。我有一个发送错误的响应,而不是抛出错误,将其删除并在抛出下面添加了响应,从而修复了该错误。

后端中的代码现在是这样:

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