简体   繁体   中英

A user login system the Node way

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.

可能您需要使用已经创建的解决方案-http://passportjs.org/

A gentle suggestion: you need to slow down and read the answers you are getting more comprehensively and also do a little more research.

Look at the code I provided, in my first answer to you about this question, which you copied, pasted, and then altered in a breaking way.

            if (rows[0].password === password) {
                // you would probably want a more useful callback result than 
                // just returning the username, but again - an example
                return callback(null, rows[0].username);
            } else {
                return callback(new Error ('Bad Password'), null);
            }

You changed this to:

            if (rows[0].password === password) {
                loginSucceed();
            } else {
                loginFail();
            }

I am not sure what motivated you to take the callbacks out of the code.

Using the code I posted, you would change the code back to what I gave you originally and then change your line in the code you posted in this question from:

validator.validate(username,password,callback);

to:

validator.validate(username,password,function(err,result){
    if (err) loginFail();
    else loginSucceed();
});

UPDATE To illustrate the access to res/req via closures.

Since the only place you are really using loginFail() and loginSucceed you could rewrite what you have this way. In this case, you don't need to worry about passing req and res to the functions because they are available via closure. I inlined the username/pass parametere for brevity

function myLoginHandler (req, res) {
    // define your functions within the myLoginHandler scope

    function loginSucceed(){
        res.writeHead(302, {'Location': 'http://localhost/officeball/app.php'});
        res.end();
    }
    function loginFail(){
        res.writeHead(302, {'Location': 'http://localhost/officeball'});
        res.end();
    }
    // and call them the same you did
    validator.validate(req.body.email, req.body.password ,function(err,result){
        if (err) loginFail();
        else loginSucceed();
    });
}
// then you just register your function as the /login handler.
function listen(){
    app.use(express.bodyParser());
    app.post('/login', myLoginHandler);
    app.listen(8080, function() {
        console.log('Server running at http://127.0.0.1:8080/');
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM