Node.js – 从MySQL查询返回值

我想在Node.js中返回MySQL查询,但是我遇到了一些问题。

Prob1。 'var userInfo'无法从函数'Authenticate()'获取值

Prob2。 抛出将被“dbclient.query”捕获,而不是我可以看到的代码。

希望大家能帮助我。


app.post('/create_member_check', function(req, res) { var Authenticate = function () { SearchUser(req.body.email, function (isExist) { if (isExist === true) throw 101; else if (req.body.email === undefined || req.body.email == "") throw 102; else if (req.body.password === undefined || req.body.password == "") throw 103; else if (isExist === undefined) throw 104; var user = { "email": req.body.email, "password": req.body.password }; AddUser(user); // This line cannot return the 'user' for 'Authenticate()' caller. return user; }); } try { var userInfo = Authenticate(); } catch (err) { var userInfo; if (err == 101) userInfo = "[Error] This account already exists."; else if (err == 102) userInfo = "[Error] Please key in 'email'."; else if (err == 103) userInfo = "[Error] Please key in 'password'."; else if (err == 104) userInfo = "[Fatal Error] SearchUser return 'undefined'."; } res.render("login_system/create_member_check", { layout: false, pagename: "create", authenticate: userInfo }); }); 

 SearchUser = function (email, callback) { dbclient.query("SELECT * FROM user WHERE email = \"" + email + "\"", function (err, results) { if (err || results.length <= 0) callback(false); else callback(true); }); } 

       

网上收集的解决方案 "Node.js – 从MySQL查询返回值"

validation方法不能同步。 你应该使asynchronous方法。 尝试这个。

 app.post('/create_member_check', function(req, res) { var Authenticate = function (req, callback) { SearchUser(req.body.email, function (isExist) { if (isExist === true) return callback(101); else if (req.body.email === undefined || req.body.email == "") return callback(102); else if (req.body.password === undefined || req.body.password == "") return callback(103); else if (isExist === undefined) return callback(104); var user = { "email": req.body.email, "password": req.body.password }; AddUser(user); //this is maybe asynchronous, again callback(null, user); }); } Authenticate(req, function(err, user){ var userInfo; if (err == 101) userInfo = "[Error] This account already exists."; else if (err == 102) userInfo = "[Error] Please key in 'email'."; else if (err == 103) userInfo = "[Error] Please key in 'password'."; else if (err == 104) userInfo = "[Fatal Error] SearchUser return 'undefined'."; res.render("login_system/create_member_check", { layout: false, pagename: "create", authenticate: userInfo }); }); }); 

并阅读这篇文章 ;)