Printing the data retrieved from database as response in node.js
Problem
I'am beginner of node.js,Sorry if I went wrong.
Instead of printing data in console.log(),I want to print at localhost:3000.
Here I retrieved data from MYsql database,Everything went right when I done with console.log().
But it went wrong when I written my code with http request and response.
My db.js is
var http = require("http");
var port = 3000;
var serverUrl = "localhost";
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : username,
password: password,
database: "wst"
});
var server = http.createServer(function(req, res) {
console.log("Request: " + req.url);
connection.connect();
connection.query('select * from welcome',function(err, results, fields){
//console.log(results);
//console.log(fields);
var html = "Registered users are " + results + ".
";
res.end(html);
});
connection.end();
});
console.log("Listening at " + serverUrl + ":" + port);
server.listen(port, serverUrl);
And the output in browser is:
Registered users are [object Object],[object Object].
And error in command prompt is:
cannot enqueue handshake after invoking quit.
If I'm completely wrong give me some tutorials on node.js.
Related Articles
Solution
Based on the comments, it sounds like you're doing some processing on the client to bind it to a template after fetching it through ajax?
Given that, you should consider not doing any templating on the server and instead just sending the json data, e.g. rather than Registered users are " + util.inspect(results) + ".
you would just do util.inspect(results)
.
You'll probably want to set the Content-Type header as well to application/json
so that any magic your clientside framework wants to do by inspecting the headers will work.
Discussion
View additional discussion.