How can I write my simple user-login system in the Node way, with callbacks?
I'm attempting to write a simple login validation script with node, but node's asynchronous callback methodology just hasn't clicked for me. I'll show my scarily bad simple login system script so you can see how lost I am with this concept. I'm just trying to grasp the concept of doing this asynchronously.
Resources:
I'm using express and node-mysql.
I set up an index and 4 simple modules: login, server, validator, and db_connect. Here's the app source:
https://gist.github.com/anonymous/9313703
Here is my login module, where my issue becomes obvious:
console.log('login module initialized');
var express = require('express');
var app = express();
var validator = require('./validator');
var username;
var password;
function loginSucceed(){
res.writeHead(302, {'Location': 'http://localhost/officeball/app.php'});
console.log('user ' + req.body.email + ' logged in successfully.');
res.end();
}
function loginFail(){
res.writeHead(302, {'Location': 'http://localhost/officeball'});
console.log('user ' + req.body.email + ' failed to validate.');
res.end();
}
function listen(){
app.use(express.bodyParser());
app.post('/login', function(req, res) {
console.log('User ' + req.body.email + ' is attempting login...');
username = req.body.email;
password = req.body.password;
validator.validate(username,password,callback);
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
}
exports.listen = listen;
In listen(), I need validate() to execute either loginFail() or loginSucceed() depending on the validation with the database, but I don't think I even went about that the right way.