最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - node.js + MySQL & JSON-result - Callback-issue & no response to client - Stack Overflow

programmeradmin1浏览0评论

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.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
// 
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: /

/***************
* 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
// 
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);
    });
};

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);
    });
};
Share Improve this question edited Dec 12, 2013 at 7:55 chollinger asked Dec 12, 2013 at 0:34 chollingerchollinger 1,1175 gold badges20 silver badges34 bronze badges 2
  • 3 +1 thx, was looking for exactly this example – Thariama Commented Apr 4, 2014 at 8:07
  • @Thariama agreed, this is just what I have been working on. – Aaron R. Commented Jul 29, 2014 at 5:25
Add a comment  | 

1 Answer 1

Reset to default 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);
发布评论

评论列表(0)

  1. 暂无评论