javascript - How can i pipe mysql data to a browser window instead of the console in Nodejs? -
hi trying output mysql data browser window instead of console, , have not clue on how in node, quite new to.
here mysql.js file: ' var mysql = require ("mysql");
var connection = mysql.createconnection({ host:"localhost", user: "root", }); connection.connect(function (err) {console.log( "successfully connected."); if (err) throw err; }); var query = connection.query("select * mytable", function (err, result, fields){ if (err) throw err; console.log('result:', result); }); connection.end();'
you need create server can connect , receive data browser. convenient , far simplest way http. can read http servers in node.js here. fist code snippet on page demonstrates http server 1 handler function, need achieve goal.
an (untested) example convenience:
// dependencies var mysql = require("mysql"), http = require("http"); // holds our query results var results; // connect database var connection = mysql.createconnection({ host: "localhost", user: "root" }); connection.connect(function(err) { if (err) throw err; console.log("connected database"); }); connection.query("select * mytable", function(err, rows, fields) { if (err) throw err; results = rows; connection.end(); // disconnect database }); // function handle browser's requests function requesthandler(req, res) { res.end(json.stringify(results)); // respond request string } // create server var server = http.createserver(requesthandler); // magic number 8080 on here port our server listens to. // can access webpage visiting address http://localhost:8080 server.listen(8080, function() { console.log("server online"); });
Comments
Post a Comment