14

I'd like to use node.js to query a mySQL-database and return the results as JSON to be used in a mobile application. Unfortunately, my request just sorta times out and the server does nothing for a good 2 minutes until the log-files show my console.log()-statements.

Also, the callback doesn't return anything as result. It's just empty.

// Check dependencies
var http = require('http');
// Create the http server.
// reference: http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/
http.createServer(function(request, response) {
    // Attach listener on end event.
    request.on('close', function() {
        console.log('request');

        // run asynchronous 
        getSQL(function(err, result) {
            console.log('json:', result);
            response.writeHead(200, {
                'Content-Type' : 'x-application/json'
            });
            // Send data as JSON string.
            response.end(result);
        });
    });
}).listen(3000);

// Access MySQL via node-mysql
// https://github.com/felixge/node-mysql
function getSQL(callback) {
    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host : 'localhost',
        user : 'user',
        password : 'pw',
        database : 'db',
        socketPath : '/var/run/mysqld/mysqld.sock', // socket for communication from debian <-> client, seems not to be set correcly by default?
    });

    connection.connect();
    var json = '';
    var query = 'SELECT * FROM test';
    connection.query(query, function(err, results, fields) {
        if (err)
            return callback(err, null);

        console.log('The result is: ', results[0]);

        // wrap result-set as json
        json = JSON.stringify(results);
    });
    connection.end();

    callback(null, json);
};

Output after like 2 minutes:

$ node app.js
request
json:
The result is:  { test: 'avc' }
json2: [{"test":"avc"}]

Based on my very basic understanding of the whole node.js-concept, my code should query the db (it does) and return a json once it's finished via the callback-function (apparently doesn't) which than is sent back as a response to the client (can't really check that since the json's empty).

I guess I made one (or a couple) major mistakes. Help and/or helpful links would be much appreciated. Thanks!

Solution, thanks to hexacyanide

// Check dependencies
var http = require('http');
// Create the http server.
// reference: http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/

/***************
* Correction 1: Using the request.on('close', function()( ... )-listener isn't required anymore
***************/
http.createServer(function(req, res) {
    console.log('Receving request...');
    var callback = function(err, result) {
        res.writeHead(200, {
            'Content-Type' : 'x-application/json'
        });
        console.log('json:', result);
        res.end(result);
    };

    getSQL(callback);

}).listen(3000);

// Access MySQL via node-mysql
// https://github.com/felixge/node-mysql
function getSQL(callback) {
    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host : 'localhost',
        user : 'user',
        password : 'pw',
        database : 'db',
        socketPath : '/var/run/mysqld/mysqld.sock', // socket for communication from debian <-> client, seems not to be set correcly by default?
    });

    connection.connect();
    var json = '';
    var query = 'SELECT * FROM test';
    connection.query(query, function(err, results, fields) {
        if (err)
            return callback(err, null);

        console.log('The query-result is: ', results[0]);

        // wrap result-set as json
        json = JSON.stringify(results);

        /***************
        * Correction 2: Nest the callback correctly!
        ***************/
        connection.end();
        console.log('JSON-result:', json);
        callback(null, json);
    });
};
2
  • 3
    +1 thx, was looking for exactly this example Commented Apr 4, 2014 at 8:07
  • @Thariama agreed, this is just what I have been working on. Commented Jul 29, 2014 at 5:25

1 Answer 1

12

You're following an older guide which instructs you to wait for the request's close event before sending the response, but you actually no longer need to do that.

What's happening is you aren't sending your response, so your client is timing out. Only until the client times out is when close events fires. Since the client has disconnected by the time you send your response, you don't get anything on the client and only see it in the terminal.

To fix this problem, just stop waiting for the close event and run code immediately when the request handler is called:

var http = require('http');
http.createServer(function(req, res) {
  getSQL(function(err, result) {
    res.writeHead(200, {
      'Content-Type' : 'x-application/json'
    });
    res.end(result);
  });
}).listen(3000);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank yo so much, works great! Would've probably taken me decades to figure that out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.