node.js + MySQL& JSON结果 - 回调问题&没有回应客户 [英] node.js + MySQL & JSON-result - Callback-issue & no response to client

查看:75
本文介绍了node.js + MySQL& JSON结果 - 回调问题&没有回应客户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用node.js查询mySQL数据库,并将结果作为JSON返回,以便在移动应用程序中使用。不幸的是,我的请求只是排序超时,服务器在2分钟内没有做任何事情,直到日志文件显示我的 console.log() -statements。

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

2分钟后输出:

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

基于我对整个node.js概念的基本理解,我的代码应该查询db(它确实)并通过回调函数(显然没有)返回一个json,而不是作为对客户端的响应发送回来(因为json的回复,所以无法真正检查)空的)。

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!

解决方案,多亏了六氰化物

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


推荐答案

您正在关注指导您的旧指南在发送响应之前等待请求的关闭事件,但实际上您不再需要这样做。

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.

要解决此问题,只需停止等待close事件并在调用请求处理程序时立即运行代码:

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

这篇关于node.js + MySQL&amp; JSON结果 - 回调问题&amp;没有回应客户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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