从数据库获取简单信息到 Node.js http 服务器响应中
我正在尝试从 db 获取简单信息到 node.js http 服务器响应中。 在下面的代码片段中,我可以在系统日志中看到数据库结果,但在 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' );
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 response.
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' );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
结束 httpResponse 后,将调用 client.query 的异步回调。尝试将最后几条语句移动到该回调中 - 例如:
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: