Haitham Laith
Haitham Laith

Reputation: 1

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

Upvotes: 0

Views: 50

Answers (2)

henktenk
henktenk

Reputation: 280

Since you are requiring express, I'm assuming you want to use it. You can create an index route with app.get('/', function(req,res){}). A fast way to display your data as json from your mysql database would be:

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

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

// localhost:7777/
app.get('/', function(req, res) {
    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];
                res.send(json); // Send the JSON back as a application/json type response.
            });
            console.log("Database is connected");
        } else {
            console.log("Error connecting database");
        }
    });
})

app.listen(7777, function() {
    console.log('Example app listening on port 7777!')
});

Upvotes: 1

e4c5
e4c5

Reputation: 53734

what does JSON.stringify do?

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

What does JSON.parse do?

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

So basically, one operation is the inverse of the other. And therein lies your problem:

var json = JSON.parse(JSON.stringify(rows))[0];

Upvotes: 1

Related Questions