社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  DATABASE

使用MySql/NodeJs处理登录系统错误用户名错误

Cesare Mannino • 4 年前 • 2286 次点击  

我有下面的控制器,我用它来管理我的应用程序上的登录系统。在所有情况下都有效,除了我插入错误用户名的情况。

我插入了以下条件语句来处理错误:

 if (error === null) {
                res.status(401).render('login', {
                    message: 'Email or Password is incorrect'
                })
            }

但当我插入它时,我会在终端上收到以下消息:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

const jwt = require('jsonwebtoken');
const mysql = require('mysql');
const bcrypt = require('bcryptjs');
const { promisify } = require('util');

var db_config = {
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_NAME
};

var connection;



function handleDisconnect() {
    connection = mysql.createConnection(db_config); // Recreate the connection, since
    // the old one cannot be reused.

    connection.connect(function (err) {              // The server is either down
        if (err) {                                     // or restarting (takes a while sometimes).
            console.log('error when connecting to db:', err);
            setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
        }                                     // to avoid a hot loop, and to allow our node script to
    });                                     // process asynchronous requests in the meantime.
    // If you're also serving http, display a 503 error.
    connection.on('error', function (err) {
        console.log('db error', err);
        if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
            handleDisconnect();                         // lost due to either server restart, or a
        } else {                                      // connnection idle timeout (the wait_timeout
            throw err;                                  // server variable configures this)
        }
    });
}

handleDisconnect();





// code in case the user leave the login space empty

exports.login = async (req, res) => {
    try {
        const { email, password } = req.body;

        if (!email || !password) {
            return res.status(400).render('login', {
                message: 'Please provide an email and password'
            })
        }

        connection.query('SELECT * FROM login WHERE email=?', [email], async (error, results) => {
        
            // conditional statement to handle the wrong username error
            if (error === null) {
                res.status(401).render('login', {
                    message: 'Email or Password is incorrect'
                })
            }
            //conditional if statement to compare password in database and password inserted by the client
            if (!results || !(await bcrypt.compare(password, results[0].password))) {
                res.status(401).render('login', {
                    message: 'Email or Password is incorrect'
                }) //conditional statement to fetch the id of the client and signign in with sign() function
            } else {
                const id = results[0].id;
                const token = jwt.sign({ id }, process.env.JWT_SECRET, {
                    expiresIn: process.env.JWT_EXPIRES_IN
                });

                // console.log('the token is:' + token);
                const cookieOptions = {
                    expires: new Date(
                        Date.now() + process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000 // 24 hours converted in milliseconds to set the expiration cookies to 24 hours
                    ),
                    httpOnly: true
                }//setting of cookies on the browser and redirecting to the user interface page
                res.cookie('jwt', token, cookieOptions);
                res.status(200).redirect('/ui');
            }

        });

    } catch (error) {
        console.log("this is the error:", error)
    }

}


exports.register = (req, res) => {

 
    // Destructor
    const { name, email, password, passwordConfirm } = req.body;
    //query that order to MySQL to get the user email only once
    connection.query('SELECT email FROM login WHERE email = ?', [email], async (error, results) => {
        if (error) {
            console.log(error);
        }
        if (results.length > 0) {
            return res.render('register', {
                message: 'That email is already in use'
            })
        } else if (password !== passwordConfirm) {
            return res.render('register', {
                message: 'Password do not match'
            });
        }

        let hashedPassword = await bcrypt.hash(password, 8);
        // console.log(hashedPassword);

        connection.query('INSERT INTO login SET ?', { name: name, email: email, password: hashedPassword }, (error, results) => {
            if (error) {
                console.log(error);
            } else {
                // console.log(results);
                return res.render('register', {
                    message: 'User registered'
                });

            }
        })

    });

}


exports.isLoggedIn = async (req, res, next) => {
    // console.log(req.cookies);
    if (req.cookies.jwt) {
        try {
            //1)verify the token
            decoded = await promisify(jwt.verify)(req.cookies.jwt,
                process.env.JWT_SECRET
            );



            //2) Check if the user still exists
            connection.query('SELECT * FROM login WHERE id = ?', [decoded.id], (error, result) => {
                // console.log(result);

                if (!result) {
                    return next();
                }
                req.user = result[0];
                return next();
            });
        } catch (error) {
            console.log(error);
            return next();
        }
    } else {
        next();
    }
}

exports.logout = async (req, res) => {
    res.clearCookie('jwt');
    res.status(200).redirect('/');
}

提前感谢您对正确路径的建议或更正。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130196
文章 [ 3 ]  |  最新文章 4 年前
Cesare Mannino
Reply   •   1 楼
Cesare Mannino    4 年前

我明白了,或者说至少正在起作用。我删除了第一个 if 语句,并对其进行修改,如下所示。而不是 !results 我把它编辑成 results == "" 。因此,如果结果为空,它将呈现 login 带着te警报 message .

if (results == "" || !(await bcrypt.compare(password, results[0].password))) {
                res.status(401).render('login', {
                    message: 'Email or Password is incorrect'
                }) //conditio
ElyasAsmad
Reply   •   2 楼
ElyasAsmad    4 年前

您需要通过将 return 关键字或代码将在其他语句中运行。

if (error === null) {
    return res.status(401).render('login', {
          message: 'Email or Password is incorrect'
    })
}

或

if (error === null) {
    res.status(401).render('login', {
          message: 'Email or Password is incorrect'
    })
    return
}
Alex
Reply   •   3 楼
Alex    4 年前

不要忘记返回响应,否则功能将继续。

return res.status(401).render('login', {
  message: 'Email or Password is incorrect'
});