get simple info from db into a node.js http server response
I am trying to get a simple info from db into a node.js http server response. In the following snippet I can see the DB results in the system log, but not in the http resp开发者_开发知识库onse.
Can you give me some ideas on why this is happening?
Thanks.
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' );
The async callback for client.query is getting called after you've ended the httpResponse. Try moving the last few statements inside that callback - e.g:
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 );
精彩评论