从db获取简单信息到node.js http服务器响应

问题描述 投票:2回答:1

我试图从db获取一个简单的信息到node.js http服务器响应。在下面的代码片段中,我可以在系统日志中看到DB结果,但在http响应中却看不到。

你能告诉我为什么会这样吗?

谢谢。

var
    sys = require( 'sys' )
    , http = require( 'http' )
    , dbParams = {
          user : 'test'
        , pass : 'test'
        , db : 'just_test'
    }
;

function dbConnect() {
    var Client = require( 'mysql' ).Client
        , client = new Client()
    ;

    client.user = dbParams.user;
    client.password = dbParams.pass;
    client.connect();
    client.query('USE ' + dbParams.db);

    return( client );
}

var dbClient = dbConnect();

http.createServer( function( httpRequest, httpResponse ) {
    httpResponse.writeHead( 200, { 'Content-Type' : 'text/plain' } );
    httpResponse.write( '=== START httpResponse' + "\n" );

    dbClient.query( 'SELECT * FROM base_events', function (err, dbRes, fields) {
        if (err) { throw err; }

        httpResponse.write( 'Obtained: ' + JSON.stringify( dbRes ) );
sys.log( 'FROM DB: ' + JSON.stringify( dbRes ) );
    } );

    httpResponse.write( '=== Test' + "\n" );
    httpResponse.end();

    dbClient.end();
} ).listen( 8000 );

sys.puts( 'Server running at http://127.0.0.1:8000' );
mysql node.js
1个回答
5
投票

在结束httpResponse之后,将调用client.query的异步回调。尝试移动回调中的最后几个语句 - 例如:

http.createServer( function( httpRequest, httpResponse ) {
    httpResponse.writeHead( 200, { 'Content-Type' : 'text/plain' } );
    httpResponse.write( '=== START httpResponse' + "\n" );

    dbClient.query( 'SELECT * FROM base_events', function (err, dbRes, fields) {
        if (err) { throw err; }

        httpResponse.write( 'Obtained: ' + JSON.stringify( dbRes ) );
    sys.log( 'FROM DB: ' + JSON.stringify( dbRes ) );

        httpResponse.write( '=== Test' + "\n" );
        httpResponse.end();

        dbClient.end();

    } );

} ).listen( 8000 );
© www.soinside.com 2019 - 2024. All rights reserved.