gpt4 book ai didi

javascript - 带 Node 的简单用户登录验证模块

转载 作者:行者123 更新时间:2023-11-29 13:10:48 25 4
gpt4 key购买 nike

我正在编写我的第一个(非教程) Node 应用程序,并且正在编写一个函数,该函数应该将用户名和密码作为参数,并根据数据库的用户表查询它们以返回 true或假。数据库已设置,应用程序已成功连接到该数据库。

但是,我没有太多地使用 SQL,也没有使用过 Node,而且我不确定如何继续使用这个函数(以及简短的周围脚本)。这是:

console.log('validator module initialized');
var login = require("./db_connect");

function validate(username, password){

connection.connect();
console.log('Connection with the officeball MySQL database openned...');

connection.query(' //SQL query ', function(err, rows, fields) {
//code to execute

});

connection.end();
console.log('...Connection with the officeball MySQL database closed.');


if(){ //not exactly sure how this should be set up
return true;
}
else{ //not exactly sure how this should be set up
return false;
}
}

exports.validate = validate;

这是使用node-mysql 。我正在寻找一个关于如何设置查询和验证的基本示例。

最佳答案

我认为您需要将您的应用程序重新考虑为一种更像 Node 的方式(即,认识到许多/大多数事情是异步发生的,因此您通常不会从这样的函数“返回”,而是执行来自它的回调。不确定您打算从node-mysql获得什么,但我可能只会使用普通的mysql模块。下面的代码仍然很可能不完全是您想要的,但希望能让您正确思考它.

请注意,下面使用“return”实际上并没有返回结果(回调本身不应该返回任何内容,因此就像返回未定义一样。有了 return 语句,您就可以退出函数,这可以节省大量时间)乏味的 if/else block 。

希望这会有所帮助,但我建议查看 github 上的各种 Node 项目,以更好地了解 Node 编写的异步特性。

function validate(username, password, callback){
var connection = mysql.createConnection({ user:'foo',
password: 'bar',
database: 'test',
host:'127.0.0.1'});

connection.connect(function (err){
if (err) return callback(new Error('Failed to connect'), null);
// if no error, you can do things now.

connection.query('select username,password from usertable where username=?',
username,
function(err,rows,fields) {
// we are done with the connection at this point), so can close it
connection.end();

// here is where you process results
if (err)
return callback(new Error ('Error while performing query'), null);
if (rows.length !== 1)
return callback(new Error ('Failed to find exactly one user'), null);

// test the password you provided against the one in the DB.
// note this is terrible practice - you should not store in the
// passwords in the clear, obviously. You should store a hash,
// but this is trying to get you on the right general path

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);
}

});


});
};

关于javascript - 带 Node 的简单用户登录验证模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22123157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com