HTTP get response with a JSON

52 views
Skip to first unread message

paolodocet

unread,
Jul 15, 2016, 5:14:50 PM7/15/16
to nodejs
I have an HTTP get request to extract from MySQL all records of a User table. 

User table looks like as follow:

+ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + -  
-      ID        +     Username      +    Email    +     Password       +
+ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - 
-               -                             -                  -                           -
+     1       +           a               +  a...@live.it   +  123456789        +   
-               -                             -                  -                           -
+ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - 
-               -                             -                  -                           -
+     2       +           b               +  b...@live.it   +  123456789        +   
-               -                             -                  -                           -
+ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - 
-               -                             -                  -                           -
+     3       +           c               +  c...@live.it   +  123456789        +   
-               -                             -                  -                           -
+ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - 

Then I create a javascript array where each element is a record of the previous table and using stringify I convert the js array in a JSON. My get response must reply with this JSON:

app.get('/getUsers', function (req, res) {

    var users= [];
    var userJSON="";


    connection.query('SELECT * FROM USER ORDER BY ID', function (err, rows, fields) {

        if (err) {
            console.log('There was an error\n' + err);
        }
        else {
            for (var i in rows) {                
                users.push({ID:rows[i].ID, Username:rows[i].Username, Email:rows[i].email, Password: rows[i].Password});
            }
            userToJson = JSON.stringify(users);
            console.log(userToJson);
        }
    });
res.setHeader('Content-Type','application/json');
res.json(userJSON);
res.end();

});

My res.json(userJSON) does not work and my response is empty. How can I send to my client the JSON properly?

Ryan Schmidt

unread,
Jul 15, 2016, 11:32:16 PM7/15/16
to nod...@googlegroups.com
You're calling res.setHeader, res.json and res.end *before* the userJSON variable has been filled with data. userJSON is not being filled with data until the anonymous function you give to connection.query runs, which won't be until the database has had time to process the query. You need to call your res functions in that anonymous function.



app.get('/getUsers', function (req, res) {

var users= [];
var userJSON="";


connection.query('SELECT * FROM USER ORDER BY ID', function (err, rows, fields) {
res.setHeader('Content-Type','application/json');
if (err) {
console.log('There was an error\n' + err);
res.json({error: err});
}
else {
for (var i in rows) {
users.push({ID:rows[i].ID, Username:rows[i].Username, Email:rows[i].email, Password: rows[i].Password});
}
userToJson = JSON.stringify(users);
console.log(userToJson);
res.json(userJSON);
}
res.end();
});

});

Marco Antonio Solís Cruz

unread,
Jul 15, 2016, 11:32:28 PM7/15/16
to nod...@googlegroups.com
Try this:

app.get('/getUsers', function (req, res) {

    var users= [];
    var userJSON="";


    connection.query('SELECT * FROM USER ORDER BY ID', function (err, rows, fields) {

        if (err) {
            console.log('There was an error\n' + err);
        }
        else {
            rows.forEach(function( item){
                users.push({ID:item.ID, Username:item.Username, Email:item.email, Password: item.Password});
            });
            userToJson = JSON.stringify(users);
            console.log(userToJson);
        }
    });
res.json(users);
}

Regards
Marco


--
Job board: http://jobs.nodejs.org/
New group rules: https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.
To post to this group, send email to nod...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/nodejs/06e3ec94-2f99-4c34-9898-79349254a5cb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ryan Schmidt

unread,
Jul 17, 2016, 7:12:58 PM7/17/16
to nod...@googlegroups.com
I was focused on the flow of your code and not on variable names. I realize now that you also have variable name confusion: you have a variable userJSON which you declare and initialize to the empty string and never modify, and then you have a second variable userToJson which you fill with data but only use in your console.log. Let's fix those issues by using only a single variable:


app.get('/getUsers', function (req, res) {

connection.query('SELECT * FROM USER ORDER BY ID', function (err, rows, fields) {
res.setHeader('Content-Type','application/json');
if (err) {
console.log('There was an error\n' + err);
res.json({error: err});
}
else {
var users = [];
for (var i in rows) {
users.push({ID:rows[i].ID, Username:rows[i].Username, Email:rows[i].email, Password: rows[i].Password});
}
var userJSON = JSON.stringify(users);
console.log(userJSON);
res.json(userJSON);
}
res.end();
});

});


Reply all
Reply to author
Forward
0 new messages