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?
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 !