Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

283
Vistas
Sqlite3, user already exists while it does not
app.post('/register', function(req,res){
  console.log("register post got", req.body)
  if (req.body.username && req.body.password) {
    db.get("SELECT * FROM Users WHERE username = '" + req.body.username + "' LIMIT 1");
    res.end("Account already exists");
    var stmt = db.prepare("INSERT INTO user VALUES (?,?)");
    stmt.run(req.body.username, req.body.password);
    res.end("OK");
  } else {
    res.end("username and password are requesiraehri");
  }
});

What's wrong here, because If I'm trying to register user, it says it already exists while the db is completely empty. Any help?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

In all that follows, I assume you are using this sqlite library: https://www.npmjs.com/package/sqlite3

res.send("Account already exists"); is called unconditionally. You forgot to check the result of your query.

But there are other issues in your code. Frist of all, you are not using async functions with callbacks. db.get is an asynchronous function and takes a callback as a second argument, which receives either the first row of the resultset or an error (see documentation).

app.post('/register', function(req,res){
  console.log("got register post", req.body)
  if (req.body.username && req.body.password) {
    db.get("SELECT * FROM Users WHERE username = ? LIMIT 1", req.body.username, function(err, row){
      if(row){
        res.end("Account already exists");
      } else {
        var stmt = db.prepare("INSERT INTO user VALUES (?,?)");
        stmt.run(req.body.username, req.body.password);
        res.end("OK");
      }
    }
  } else {
    res.end("username and password are required");
  }
});

stmt.run is also asynchronous. So be aware, that res.end('OK') is executed before the data is inserted into the database. It would be probably better to check if the insert statement is run successfully before sending the response.

Another important issue is that you insert the password in clear in the database. You should think about crypting it. Never store passwords in cleartext !

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda