简体   繁体   English

从MySQL服务器获取到Node.js程序后,如何通过response.write方法写入数据?

[英]How can I write data by method response.write after got from MySQL server to a Node.js program?

I'm developing a small web app by NodeJS and I'm stuck at this point. 我正在通过NodeJS开发一个小型Web应用程序,但目前还停留在这个位置。 Please review my code: 请查看我的代码:

var config = require('./config.json');
var mysql = require('mysql');
var http = require('http');
var url = require('url');

http.createServer(function(request, response){
    var path = url.parse(request.url).pathname;
    if (path=='/ajax.html') {
        displayData(function(result) {
             console.log('Result' + result);
             response.write(result, 'utf8');
        });
    }
});


function displayData(callback) {
    var connection = mysql.createConnection({
        host     : config.host,
        user     : config.user,
        password : config.password,
        database : config.database,
    });
    connection.connect();
    var query = connection.query("SELECT name FROM `table` WHERE `id` = '1'");  
    query.on('result', function(row) {
        callback(row.name);
    });
}

I tested and realised that the response object in displayData is not itself anymore so that I am just able to view my result data in console.log and can not use response.write to view it in browser. 我测试并意识到displayData中的响应对象本身本身已不再存在,因此我只能在console.log中查看结果数据,而不能使用response.write在浏览器中查看它。

Please help what should I do to solve this problem? 请帮我该怎么做才能解决这个问题?

完成向其中写入数据后,您必须调用response.end()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM