Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

282
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!