0

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?

1
  • as far as i know response.end is used to send last bits in the stream.You should first write in the stream using response.write and then only end.(you are doing this in a loop) Commented Mar 9, 2016 at 15:40

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

This is a very great explanation. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.