gpt4 book ai didi

javascript - Node.js 从一个模块传递变量/对象并返回它

转载 作者:行者123 更新时间:2023-11-30 21:04:07 24 4
gpt4 key购买 nike

我正在使用 node.js express 框架,最初在一个路由文件中编写了获取数据库密码/哈希和比较表单密码/哈希的方法。现在我想将 userName 传递给一个单独的模块。该模块应接受 userName 并从数据库返回相应的密码/哈希。

在将函数分解为各自的模块之前,我们返回哈希并将其传递给下一个函数 (passHash),代码运行良好。现在我已经将函数与数据库调用分开,我不知道如何将散列返回到原始函数。

通过将函数分解为两个单独的文件,我可以成功地将 userName 传递给数据库模块(它控制台记录 username/hash),但我无法将用户的密码/哈希返回到原始路由中的原始函数。我读过很多关于如何使用 require 将“OR”返回变量/对象从一个模块传递到另一个模块的文章,但没有关于如何传递变量“AND”返回后置函数数据的文章。

以下是我在创建这些文件时引用的一些资源

1.) Accepted answer was easy to follow (this is the model I used)

2.) Advanced

3.) Example most answers show one way return functions

4.) Seems to have the answer

此外,我已经尝试通过多种方式返回密码/哈希值;创建一个对象并返回属性。返回对象,并将对象分配给变量并提取类似于上面链接 4 的属性。

以下是:

1.) 模块化数据库函数(databaseLoginUser.js)

2.) 调用模块化函数的原始路由(databaseLogin.js)

3.) 控制台输出(没有错误只是挂起等待下一个函数)

//databaseLoginUser.js

var express = require('express');
var router = express.Router();
var mysql = require('mysql');

module.exports.getModuleFunction = function(userName, callback) {
queryUser(userName);

function queryUser(userName) {
console.log('In Query User; ');
var database = mysql.createConnection({
host: "xxx.xxx.xxx.xxx",
port: "3306",
user: "UserName",
password: "Password",
database: "Students",
multipleStatements: true
});

database.connect();

console.log('test');

database.query('SELECT StudentUsername, StudentPassword FROM STUDENT WHERE StudentUsername = ?', userName, function(err, rows, fields) {
if (err) {
console.log(err);
}
//console.log(rows);
console.log('Database Returned User: ' + rows[0].StudentUsername);
console.log('Database Returned Password: ' + rows[0].StudentPassword);
var hashFromDatabaseBuffer = Buffer.from(rows[0].StudentPassword);
returnPassHash(hashFromDatabaseBuffer);
return returnPassHash;
})

function returnPassHash(hashFromDatabaseBuffer) {
console.log('Do I get here?; ');
return hashFromDatabaseBuffer;
}
}
};

queryPass 是调用并返回其他模块的密码属性的函数,我已经用几种不同的方式编写了它,但为了简洁起见,我决定发布这个版本的函数调用。

//loginUser.js
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var bodyParser = require('body-parser');
var async = require('async');
var app = express();
var expressValidator = require('express-validator');
var securePassword = require('secure-password');
var database = require('./db');
var queryPass = require('./databaseLoginUser');

router.get('/', function(req, res, next) {
'use strict';
console.log('in the login user get route');
res.render('signUp');
});

router.post('/', function(req, res, next) {
'use strict';
console.log('in Login Route');
var userName = req.body.userName;
var preHashPass = req.body.password;

queryPass.getModuleFunction(userName, function(data) {
passHash('', '', data)
});

function passHash(userName, preHashPass, hashFromDatabaseBuffer) {
// Initialise our password policy
var pwd = securePassword()
var postPassHash = Buffer.from(preHashPass);

// Register user
pwd.hash(postPassHash, function(err, hash) {
if (err) throw err
// Save hash somewhere
console.log('Form Password Hashed:');
console.log(hash);

pwd.verify(postPassHash, hashFromDatabaseBuffer, function(err, result) {
console.log('Verify Result: ');
console.log(result);
if (err) throw err
if (result === securePassword.INVALID) {
return res.render('index');
return console.log('Imma call the cops')
res.render('index');
} else {
if (result === securePassword.INVALID_UNRECOGNIZED_HASH) return console.error('This hash was not made with secure-password. Attempt legacy algorithm')
if (result === securePassword.VALID) console.log('Yay you made it')
if (result === securePassword.VALID_NEEDS_REHASH) {
console.log('Yay you made it, wait for us to improve your safety')

pwd.hash(hashFromDatabase, function(err, improvedHash) {
if (err) console.error('You are authenticated, but we could not improve your safety this time around')

// Save improvedHash somewhere
hash = improvedHash;
})
}

var verifiedHash = hash;
console.log('verifiedHash: ');
console.log(verifiedHash);

//Give User Auth Token Here
console.log('You Get an auth Token: ');
res.render('studentDash');
}

}) // pwd.verify


});
pwd.hash
}; // pass hash
})

module.exports = router;

来自服务器的控制台输出(注意密码是虚拟数据)

控制台输出

[nodemon] starting node ./bin/www 
GET /LogoWithLayersTiny.png 304 1.124 ms - -
in Login Route
In Query User;
test
Database Returned User: bb
Database Returned Password: "HashParametersRemoved"$WItArkxi20QeSHlGhUK2lQ$PY74Axv6cOvFD‌​FiHmZ6EwT0RMgLkDOb1W‌​6CVBssE1tk
Do I get here?

最佳答案

我认为您只需要在传递数据的 databaseLoginUser.js 中调用 callback 即可。像这样:

// databaseLoginUser.js

var express = require('express');
var router = express.Router();
var mysql = require('mysql');

module.exports.getModuleFunction = function (userName, callback) {
queryUser(userName);
function queryUser(userName) {
console.log('In Query User; ');
var database = mysql.createConnection({
host: "xxx.xxx.xxx.xxx",
port: "3306",
user: "UserName",
password: "Password",
database: "Students",
multipleStatements: true
});

database.connect();

database.query('SELECT StudentUsername, StudentPassword FROM STUDENT WHERE StudentUsername = ?', userName, function (err, rows, fields) {
if (err) { console.log(err); }
console.log('Database Returned User: ' + rows[0].StudentUsername);
console.log('Database Returned Password: ' + rows[0].StudentPassword);
var hashFromDatabaseBuffer = Buffer.from(rows[0].StudentPassword);
callback(hashFromDatabaseBuffer); // This call.
});
}
};

关于javascript - Node.js 从一个模块传递变量/对象并返回它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46842624/

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