1

I have a function onRequest(request,response) which contains a callback function. When I try to print the data using response object (i.e. response.write()) in the callback function, its not printing. But the same data is printing on the console using console.log() Please help with why the response.write() is not working.

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.");

1 Answer 1

2

Quite possibly your response has already ended.

Try

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
        }

    });
Sign up to request clarification or add additional context in comments.

2 Comments

Glad you got it working! Mark my answer as correct maybe? :) Thanks
This will end after the first result is sent though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.