Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

286
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda