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.");
Quite possibly your response has already end
ed.
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
}
});