Node.js Express /路由和mysql [英] nodejs express/routes and mysql

查看:156
本文介绍了Node.js Express /路由和mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个小问题。我正在尝试制作一个小的API,以检查用户是否已存在于我的数据库中。

I'm facing a little problem. I'm trying to make a small API to check if a user already exists in my DB.

我使用快递和路线,因此可以查询 http://example.com/check/user/john ,它应该输出:true或false,具体取决于用户是否存在于数据库中。

I use express and routes so i can query like "http://example.com/check/user/john" and it should output : true or false depending if the user exists or not in the DB.

在我的路由文件中,我的代码如下:

In my route file i have the code below :

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',{输出:输出}); 始终输出: false ,但是在我的控制台日志中它显示 true 用户已经存在。

The problem is that res.render('register/check_username', { output: output}); will always output : false, but in my console log it shows true when the user already exists.

为什么不更新输出变量?

Any idea of why the output variable isn't updated ?

如akaphenom所述,pool.getConnection被初始化为非阻塞进程,因此我的第一个代码自动将输出作为false发送。这是工作代码:

Solution : As explained by akaphenom, the pool.getConnection was beeing initialized into a non-blocking process and therefore my first code was automaticaly sending output as false. Here's the working code :

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


推荐答案

我相信您不允许非阻塞性这些电话中。将该变量设置为false,将调用连接,然后挂起挂起,等待回调。您可以在回叫完成之前立即呈现响应。

I believe you not allowing for the non-blocking nature of these calls. The variable is set to false the connection is called and then falls through pending a call back. You immediately render the response, prior to the call back completing.

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后才调用它。

Why do you get the right value in the console? Because eventually the callback is called and performs what you expect. It is just called after the res.render

此代码更可能是您想要的代码:

THis is more likely the code you want:

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

这篇关于Node.js Express /路由和mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆