I am trying to display data in JSON format on the browser! any suggestions .... i have given my javascript (.js) code below
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");