I am trying to display data in JSON format on the browser! any suggestions .... i have given my javascript (.js) code below
var http = require('http'),
mysql = require("mysql");
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'node'
});
http.createServer(function (request, response)
{
request.on('end', function ()
{
connection.query('SELECT id, content FROM test WHERE id IN (?, ?)',[1, 2], function(error, rows, fields)
{
response.writeHead(200);
response.end(JSON.stringify(rows));
});
});
}).listen(8080);
my problem is :: nodejs server is running but i am not able to display JSON data on the browser ... any suggestions on how to resolve it !
This is a 100% working code for your question ! !
var http = require('http');
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'node'
});
console.log('MySQL Connection details '+connection);
http.createServer(function (request, response)
{
console.log('Creating the http server');
connection.query('SELECT id, content FROM test WHERE id IN (?,?)',[1, 2], function(err, rows, fields)
{
console.log('Connection result error '+err);
console.log('no of records is '+rows.length);
response.writeHead(200, { 'Content-Type': 'application/json'});
response.end(JSON.stringify(rows));
response.end();
});
}).listen(8084);
I have even added the snapshot's below
command prompt where the execution is done below

JSON output seen in the browser below

Add a content-type in your code:
response.setHeader("Content-Type", "application/json");