3

I'm trying to check if a user in the database also exists. My code works if I add a user to the db without checking if someone with it's name exists. The problem appears when I try to check it, because the code can recognize if a user exists or not, but the user cannot be added to the database if this doesn't exist. The code which works is this one (the function DB() is where the code creates the connection with the database):

app.post('/Registro', function(req, res){
var conDB=DB();
var reg={
    Usuario: req.body.Usuario,
    Contra: req.body.Contra
};
console.log(req.body.Usuario+" "+req.body.Contra);
var query=conDB.query('INSERT INTO Usuario SET ?',reg,function(err, res){

});
res.send("Usuario: "+req.body.Usuario+" y Contraseña: "+req.body.Contra + "REGISTRADOS");
conDB.end(); });

The code which doesn't work (where I'm trying to check if the user exists) is this one:

app.post('/Registro', function(req, res){
var conDB=DB();
var reg={
    Usuario: req.body.Usuario,
    Contra: req.body.Contra
};
var UsuarioReg=req.body.Usuario;
conDB.query('SELECT * FROM Usuario WHERE Usuario = ?', UsuarioReg,function(err,rows){
    if(err)
        return console.log(err);
    if (!rows.length)
    {
            conDB.query('INSERT INTO Usuario SET ?',reg,function(err, respuesta){
            return respuesta.send("Usuario: "+req.body.Usuario+" y Contraseña: "+
                    req.body.Contra + "REGISTRADOS");
            }); 
    }
    else
    {
        return res.send("Este usuario ya existe");
    }
});
    conDB.end(); 
});

If someone knows how can I solve this situation, I'd be grateful!

I have made an edition which threw this exception:

enter image description here

2 Answers 2

4

I bet the database connection is closing before the queries get executed. I'd move conDB.end() into the err handler from the first query and into the callback function of the second query.

EDIT:

app.post('/Registro', function(req, res){
    var conDB=DB();
    var reg={
        Usuario: req.body.Usuario,
        Contra: req.body.Contra
    };
    var UsuarioReg=req.body.Usuario;
    var ContraReg=req.body.Contra;
    conDB.query('SELECT * FROM Usuario WHERE Usuario = ? and Contra= ?',  [UsuarioReg,ContraReg]
,function(err,rows){
    if(err) {
        conDB.end();
        return console.log(err);
    }

    if (!rows.length)
    {
        conDB.query('INSERT INTO Usuario SET ?',reg,function(err, results){
            conDB.end();
            return res.send("Usuario: "+req.body.Usuario+" y Contraseña: "+
                req.body.Contra + "REGISTRADOS");
        });
    }
    else
    {
        conDB.end();
        return res.send("Este usuario ya existe");
    }
});

});
Sign up to request clarification or add additional context in comments.

13 Comments

I have changed the code but it still doesn't work. What I did was taking out the part that says return res.send("Usuario: "+req.body.Usuario+" y Contraseña: "+req.body.Contra + "REGISTRADOS"); from the function that adds the user to the database. There must be a problem with that function. Cannot I ask two times to the database without closing the connection in Node.js??
You definitely can. Are you seeing an error from the first query in the console? Or are you getting the user already exists response?
When the user already exists, it throws me a message that says it exists. But now, having the return down the function like the first situation which is working well, it doesn't throw an error. It only says that the new user was registered but, when I open the database, it doesn't appear
Another problem I just saw: after you attempt to insert in your callback function you have res as the second parameter. You are trying to send an http response with res, but you are overriding that variable so res isn't the HTTP response at this point
What variable are you saying that I'm overheading? The once that you can see when I use the function res.send in the places like req.body.Usuario and req.body.Contra?
|
2

Thank for your idea. It is help for me. Then I can make route for sign up in my code.

            var express = require("express");
            var router = express.Router();
            //var usersModel = require("../models/users");
            var db = require("../common/database");
            var conn = db.getConnection();
            router.get("/", function (req, res) {
                res.json({ "message": "This is Admin page" });
            })
            router.get("/register_success/:email", function (req, res) {
                res.render("register_success", { email: req.params.email });
            })
            router.get("/signup", function (req, res) {
                res.render("signup", {
                    data: {
                        email: "",
                        password: "",
                        first_name: "",
                        last_name: ""
                    }, error: false, message: ""
                });
            })
            router.post('/signup', function (req, res) {
                var user = req.body;
                var Oneuser = {
                    email: user.email,
                    password: user.passwd,
                    first_name: user.firstname,
                    last_name: user.lastname,
                    created_at: new Date()
                };
                conn.query('SELECT * FROM users WHERE email = ?', [Oneuser.email]
                    , function (err, rows) {
                        if (err) {
                            conn.end();
                            console.log(err);
                            res.render("signup", {
                                data: {
                                    email: user.email,
                                    password: user.passwd,
                                    first_name: user.firstname,
                                    last_name: user.lastname
                                }, error: true, message: err
                            });
                        }
                        if (!rows.length) {
                            conn.query('INSERT INTO users SET ?', Oneuser, function (err2, results) {
                                if (err2) {
                                    console.log(err2);
                                    res.render("signup", {
                                        data: {
                                            email: user.email,
                                            password: user.passwd,
                                            first_name: user.firstname,
                                            last_name: user.lastname
                                        }, error: true, message: err2
                                    });
                                } else {
                                    res.redirect("/admin/register_success/" + Oneuser.email);
                                }
                            });
                        }
                        else {
                            console.log("Email is exists");
                            res.render("signup", {
                                data: {
                                    email: user.email,
                                    password: user.passwd,
                                    first_name: user.firstname,
                                    last_name: user.lastname
                                }, error: true, message: "Email is exists"
                            });
                        }
                    });
            });
            module.exports = router;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.