Thursday, 11 May 2017

nodeJS - how i connect with MySQL and display the result in localhost

I wrote this code

var http = require('http');
var express = require('express');
var mysql = require('mysql');

var connection = mysql.createConnection({
  host: '127.0.0.1',
  user: 'root',
  password: '',
  database: 'nodejs'
});

connection.connect(function (err) {
  if (!err) {
    connection.query('SELECT * FROM nodetest', function (err, rows) {
      if (err) {
        console.log(err);
        return;
      }
      var json = JSON.parse(JSON.stringify(rows))[0];
      console.log(json);
    });
    console.log("Database is connected");
  } else {
    console.log("Error connecting database");
  }
});



http.createServer(function (request, response) {
  response.writeHead(200, {
    "Content-Type": "test/html"
  });
  response.end('here my data');
}).listen(7777);

and I have a problem with display the result in my localhost as i json what is the bast way to read table and convert it to json and display in localhost



via Haitham Laith