如何从 node.js 中的 mysql SELECT 查询返回值 [英] How to return a value from a mysql SELECT query in node.js

查看:35
本文介绍了如何从 node.js 中的 mysql SELECT 查询返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Node.js 还是很陌生,我正在尝试了解回调是如何工作的.所以,这是我的问题:

I'm still very new to Node.js, and i'm trying to understand how callbacks work. So, here is my problem :

我应该放更多代码:

发布:

app.post('/register', function(req, res) {

    //get data from the request
    var data = {
        username: req.body.username,
        email: req.body.email,
        password: req.body.password
    };

    function fetchID(callback) {
        connection.query('SELECT id_user FROM USERS WHERE username = ?', data.username, function(err, rows) {
            if (err) {
                callback(err, null);
            } else 
                callback(null, rows[0].id_user);
        });
    }
    var user_id;
    fetchID(function(err, content) {
        if (err) {
            console.log(err);
            return next("Mysql error, check your query");
        } else {
            user_id = content;
            console.log(user_id); //undefined
        }
    });

    console.log(user_id); //undefined
    var payload = {
        iss: req.hostname,
        sub: user_id
    }
    console.log(payload.sub); //correct id
})

获取:

app.get('/todos', function(req, res) {
    if (!req.headers.authorization) {
        return res.status(401).send({
            message: 'You are not authorized !'
        });
    }

    var token = req.headers.authorization.split(' ')[1];
    var payload = jwt.decode(token, "shhh..");

    //additional level of security
    console.log('sub id is : ' + payload.sub); //undefined
    if (!payload.sub) {
        return res.status(401).send({
            message: 'Authentication failed !'
        });
    }

})

我对每个 console.log 进行了注释以使其更加清晰.当我在 app.get()

I commented each console.log to be more clear. I need to get the correct id when i check for if (!payload.sub) in app.get()

推荐答案

你的两个函数应该是这样的 -

Your two functions should be something like -

function fetchID(data, callback) {
        connection.query('SELECT id_user FROM USERS WHERE username = ?', data.username, function(err, rows) {
            if (err) {
                callback(err, null);
            } else 
                callback(null, rows[0].id_user);
        });
}

然后

var user_id;

fetchID(data, function(err, content) {
    if (err) {
        console.log(err);
        // Do something with your error...
    } else {
        user_id = content;
    }
});

在回调函数中,返回的变量content 将保存user_id 的值.

Here in the callback function, the returned variable content will hold the value for user_id.

编辑

我还没有解决你上面描述的确切问题.

I have not solved the exact problem as you had described above.

但是在下面的例子中,我已经证明了回调机制是有效的 -

But in following example, I have shown that, the callback mechanism is working -

首先(创建表格并插入一些虚拟数据)-

use test;
create table users (id int(11) primary key,username varchar(100));
insert into users values(1, "John");
insert into users values(2, "Sham");

现在我已经将您的 post 方法设置为 get 并在浏览器中进行了测试.

Now I have made your post method as get and tested in browser.

以下是在我的本地主机中测试的完整类 -

Following is the full class tested in my localhost -

var application_root = __dirname,
    express = require("express"),
    mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
  host : 'localhost',
  user : 'root',
  password : 'admin',
  database: "test"
});
app.get('/getuser', function(req, res) {
  //get data from the request
    var data = {
        username: req.query.username
    };
    function fetchID(data, callback) {
        connection.query('SELECT id FROM users WHERE username = ?',        
               data.username, function(err, rows) {
            if (err) {
                callback(err, null);
            } else 
                callback(null, rows[0].id);
        });
    }
    var user_id;
    fetchID(data, function(err, content) {
        if (err) {
        console.log(err);
        res.send(err);  
        // Do something with your error...
        } else {
        user_id = content;
        console.log(user_id);
        res.send("user id is -" + user_id);
        }
    });
})
app.listen(1212);

现在这些请求将产生这个输出——http://127.0.0.1:1212/getuser?username=john => user id is -1http://127.0.0.1:1212/getuser?username=sham => user id is -2

Now these requests will produce this output - http://127.0.0.1:1212/getuser?username=john => user id is -1 and http://127.0.0.1:1212/getuser?username=sham => user id is -2

希望这个代码示例能帮助你理解 node.js 中的回调.

Hope this code example will help you to understand the callback in node.js.

谢谢

这篇关于如何从 node.js 中的 mysql SELECT 查询返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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