简体   繁体   中英

Express redirect error: can't set headers after they are sent using NodeJS and MySQL

When this code hits the redirect line inside the catch function. I get an error

Can't set header after they are sent

In the try function it checks if the email exists in the database and once it runs it will take the user email and assign it to a clusters table in the database.

The problem is when the email doesn't exist, I try to redirect it to the register form html template -> res.redirect("/") but it won't let me

I saw multiple people say that using return would easily solve the issue but I've tried doing return res.redirect("/") and that didn't work.

router.post("/get-user-cluster", (req, res) => {
    const email = req.body.check_email;
    var retrievedEmail;
    var availCluster;

    const queryEmail = 'SELECT * FROM users WHERE email = ?';
    const queryAvailableCluster = 'SELECT * FROM clusters WHERE clusters_email IS NULL LIMIT 1';
    const querySetEmailCluster = "UPDATE clusters SET clusters_email = ? WHERE id = ? ";

    getConnection().query(queryEmail, [email], (err, data, fields) => {

        try {
            if (err) {
                console.log("Failed to query for user email: " + err)
                return
            } 

            retrievedEmail = data[0].email;

            getConnection().query(queryAvailableCluster, (err, data, fields) => {
                if (err) {
                    console.log("Failed to query for available cluster: " + err)
                    return
                } 

                availCluster = data[0].id;

                getConnection().query(querySetEmailCluster, [retrievedEmail, availCluster], (err, data, fields) => {
                    if (err) {
                        console.log("Failed to query for assigning user email to available cluster: " + err)
                        return
                    } 

                });

            });
        }

        catch(err) {
            console.log('catch');
            return res.redirect('/user-form');
        }

    })
    res.end()
});

The problem is that the res.end() will be executed before your callback function, as it presents an asynchronous operation. So basically when the execution reaches the return res.redirect('/user-form'); , the response is already sent. You can move the res.end() inside the callback function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM