【问题标题】:Scope of response object in node js while using callback function使用回调函数时节点js中响应对象的范围
【发布时间】:2014-11-01 08:27:26
【问题描述】:

我有一个 onRequest(request,response) 函数,它包含一个回调函数。当我尝试在回调函数中使用响应对象(即 response.write())打印数据时,它不会打印。但是使用 console.log() 在控制台上打印相同的数据请帮助解释为什么 response.write() 不起作用。

var http = require("http");
var _mysql = require("mysql");

function onRequest(request, response) {

    console.log("Request received.");
    response.writeHead(200, {
        "Content-Type": "text/plain"
    });
    response.write("Hello World");
    var _mysql = require('mysql');

    var HOST = 'localhost';
    var PORT = 3306;
    var MYSQL_USER = 'root';
    var MYSQL_PASS = 'root';
    var DATABASE = 'library_management';
    var TABLE = 'book_details';

    var mysql = _mysql.createConnection({
        host: HOST,
        port: PORT,
        user: MYSQL_USER,
        password: MYSQL_PASS,
    });

    mysql.query('use ' + DATABASE);

    mysql.query('select * from ' + TABLE + ' where price < 1212',
        function(err, result, fields) {
            if (err) throw err;
            else {
                console.log('Books less than 1212');

                for (var i in result) {
                    var book = result[i];
                    response.write("Hello");
                    console.log(book.title + ':' + book.price);
                    //above is working
                    response.write(book.title + ':' + book.price);
                    //above is not working...why?
                }
            }

        });


    response.end();
}

http.createServer(onRequest).listen(8888);

console.log("Server has started.");

【问题讨论】:

    标签: javascript node.js web


    【解决方案1】:

    很可能您的回复已经ended。

    试试

    mysql.query('select * from ' + TABLE + ' where price < 1212',
        function(err, result, fields) {
            if (err) throw err;
            else {
                console.log('Books less than 1212');
    
                for (var i in result) {
                    var book = result[i];
                    response.write("Hello");
                    console.log(book.title + ':' + book.price);
                    //above is working
                    response.write(book.title + ':' + book.price);
                    //above is not working...why?
                }
                response.end();//don't end response until data is written
            }
    
        });
    

    【讨论】:

    • 很高兴你能成功!可能将我的答案标记为正确? :) 谢谢
    • 这将在发送第一个结果后结束。
    猜你喜欢
    • 1970-01-01
    • 2019-11-16
    • 2018-07-15
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 2021-10-29
    相关资源
    最近更新 更多