Nasser
Nasser

Reputation: 2140

Displaying data retrieved from MySQL databased in node js

In the following code, I am trying to retrieve data from MySQL and display them in HTML page. I tested the connection by showing the data in the console and it worked fine but the problem is that the data cannot be displayed on the HTML page:

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

http.createServer(function (request, response) {

   response.writeHead(200, {'Content-Type': 'text/plain'});

   //response.end('Hello World\n');

   var connection = mysql.createConnection(
    {
      host     : 'localhost',
      user     : 'root',
      password : 'somepass',
      database : 'Students',
    }
);

connection.connect();

var queryString = 'SELECT * FROM Student';

connection.query(queryString, function(err, rows, fields) {
    if (err) throw err;

    for (var i in rows) {
        response.end('Name: ', rows[i].Name); //this doesn't work, it only shows Name: but doesn't show the retrieved name from the databased
        console.log('Name: ', rows[i].Name); //this works fine
    }
});

}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');

Can anybody help me solving this issue?

Upvotes: 0

Views: 76

Answers (1)

Stian
Stian

Reputation: 695

Have you read the documentation?

First of all, response.end takes three optional arguments: data, encoding and callback. What you are doing, is sending the data "Name: ", the encoding 'rows[i].Name'. That causes a problem in it self.

In addition, you call this method in a for loop, which means the first time .end is called, you stop sending more. As it says in the documentation, .end signals the end of data transfer, and that no more data is coming (But it is in your case).

What you should do in stead, is to use response.write("Name: " + rows[i].Name); You should make note of the following:

  1. I use .write, not .end, which means I can keep adding data to be sent.
  2. I use a +, and not a comma. That means I append the string rows[i].Name to the string "Name: ", so the final result will be "Name: ".

Finally, when the for loop is done, you should call response.end() with no arguments, indicating that you are finished with the message to be sent.

Hope this helps, and take a closer look at the documentation next time as it will probably explain these things quite clearly :) Happy programming!

Upvotes: 1

Related Questions