我面临一个小问题。我尝试制作一个小API来检查用户是否已存在于我的数据库中。
我使用快递和路线,所以我可以查询" http://example.com/check/user/john"它应输出:true或false,具体取决于用户是否存在于DB中。
在我的路线文件中,我有以下代码:
var mysql = require('mysql');
var pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '123456',
database: 'nodejs'
});
module.exports = function(app){
app.get('/register/check/u/:username', function(req, res){
var output = 'false';
pool.getConnection(function(err, conn) {
query = conn.query('SELECT * FROM users WHERE username LIKE ?', [req.params.username]);
query.on('error', function(err){
throw err;
});
query.on('result', function(row){
var output = 'true';
console.log(row.email);
console.log(output);
});
conn.release();
});
res.render('register/check_username', { output: output});
});
);
问题是res.render('register/check_username', { output: output});
将始终输出:false
,但在我的控制台日志中,当用户已存在时,它会显示true
。
知道为什么输出变量没有更新?
解决方案: 正如akaphenom所解释的那样,pool.getConnection被初始化为一个非阻塞进程,因此我的第一个代码是自动发送输出为false。这是工作代码:
app.get('/register/check/u/:username', function(req, res){
pool.getConnection(function(err, conn) {
var output = 'false';
query = conn.query('SELECT * FROM users WHERE username LIKE ?', [req.params.username]);
query.on('error', function(err){
throw err;
});
query.on('result', function(row){
output = 'true';
});
query.on('end', function(result){
res.render('register/check_username', { output: output});
});
conn.release();
});
});
答案 0 :(得分:4)
我相信你不允许这些电话的非阻塞性质。该变量设置为false,连接被调用,然后通过挂起回调。您可以在回叫完成之前立即呈现响应。
module.exports = function(app){
app.get('/register/check/u/:username', function(req, res){
// you set the value of the output var
var output = 'false';
// this is a non-blocking call to getConnection which fires the callback you pass into it, once the connection happens. The code continues on - it doesn't wait.
pool.getConnection(function(err, conn) {
query = conn.query('SELECT * FROM users WHERE username LIKE ?', [req.params.username]);
query.on('error', function(err){
throw err;
});
query.on('result', function(row){
var output = 'true';
console.log(row.email);
console.log(output);
});
conn.release();
});
// you are getting here before the callback is called
res.render('register/check_username', { output: output});
});
);
为什么在控制台中获得正确的值?因为最终会调用回调并执行您期望的操作。它只是在res.render之后调用
这更像是你想要的代码:
module.exports = function(app){
app.get('/register/check/u/:username', function(req, res){
pool.getConnection(function(err, conn) {
query = conn.query('SELECT * FROM users WHERE username LIKE ?', [req.params.username]);
query.on('error', function(err){
throw err;
});
query.on('result', function(row){
var output = 'true';
console.log(row.email);
console.log(output);
res.render('register/check_username', { output: output});
});
conn.release();
});
});
);