Home > Software engineering >  Modify HTML from NodeJS mySQL
Modify HTML from NodeJS mySQL

Time:12-05

I am new to NodeJS and MySQL, so I am trying this: I have created a table which is connected with nodejs. I succesfuly managed to console log an item that I wanted. I have also started a localhost server on port 3000 where I managed to add an h1 element to the html. However, I can't seem to find a add the result in the h1. In this case I have a random word in my database which I want to be displayed as H1.

JS:

var mysql = require('mysql');

var con = mysql.createConnection({
host: "*****",
user: "root",
password: "*****",
database: "mydb"
});

var http = require('http');  
var url = require('url');  
var fs = require('fs');  

var server = http.createServer(function(request, response) {  
  con.connect(function(err) {
    if (err) console.log(err);
    con.query("SELECT * FROM customers", function (err, result, fields) {
      if (err) console.log(err);
      console.log(result[1].name);
    })
  });
  
    var path = url.parse(request.url).pathname;  
    switch (path) {  
      case '/':  
      response.writeHead(200, {  
        'Content-Type': 'text/plain'  
      });  
      response.write("This is a Test Message.");  
      response.end();  
      break;  
      case '/index.html':  
      fs.readFile(__dirname   path, function(error, data) {  
        if (error) {  
          response.writeHead(404);  
          response.write(error);  
          response.end();  
        } else {  
          response.writeHead(200, {  
            'Content-Type': 'text/html'  
          });
          response.write(data);
          response.write("<html>")
          response.write("<h1>Added this with NodeJS!</h1>")
          response.write("</html>")
          response.end();  
        }  
      });  
      break;  
      default:  
      response.writeHead(404);  
      response.write("opps this doesn't exist - 404");  
      response.end();  
      break;  
    }  
});  

  server.listen(3000);

I tried to add the result this way, but it didn't work. I got an error saying that result is not defined.

          response.write("<html>")
          response.write("<h1>")
          response.write("His name is:"   result[1].name)
          response.write("</h1>")
          response.write("</html>")

CodePudding user response:

result is a variable defined in the query callback function:

con.connect(function(err) {
  if (err) console.log(err);
  con.query("SELECT * FROM customers", function (err, result, fields) {
    if (err) console.log(err);
    console.log(result[1].name);
  })
});

It doesn't exist OUTSIDE that callback, even though to the untrained eye it might seem like it should.

There are many different ways to get the data where you need it such as using promises to resolve your sql query when it has completed, and use the result to populate your http response. But a quick and dirty way is to just shove your http response in that callback:

var http = require('http');  
var url = require('url');  
var fs = require('fs');  

var server = http.createServer(function(request, response) {  
  con.connect(function(err) {
    if (err) console.log(err);
    con.query("SELECT * FROM customers", function (err, result, fields) {
      if (err) console.log(err);
      console.log(result[1].name);
      var path = url.parse(request.url).pathname;  
      switch (path) {  
        case '/':  
          response.writeHead(200, {  
            'Content-Type': 'text/plain'  
          });  
          response.write("This is a Test Message.");  
          response.end();  
          break;  
        case '/index.html':  
          fs.readFile(__dirname   path, function(error, data) {  
            if (error) {  
              response.writeHead(404);  
              response.write(error);  
              response.end();  
            } else {  
              response.writeHead(200, {  
                'Content-Type': 'text/html'  
              });
              response.write(data);
              response.write("<html>")
              response.write(`<h1>${response[1].name}</h1>`)
              response.write("</html>")
              response.end();  
            }  
          });  
          break;  
        default:  
          response.writeHead(404);  
          response.write("opps this doesn't exist - 404");  
          response.end();  
          break;  
      }  
    });
  });
});  

server.listen(3000);

To be clear: this is not the "right" way to do this, and definitely not an elegant way. It is a proof of concept.

CodePudding user response:

Variable result is not available in the scope you are trying to use it in, hence you get an error saying it's undefined.

result should be available in the scope you are trying to use it in that is your request handler (the top function). You can do so by declaring it in the handlers' scope. This is an example, you can use a different name of course:

let data;

// inside the query callback
data = result

However, this solution makes error handling hard.

Try using promises instead with then() or async / await along with catch():

See this answer, or use mysql2 package if you can.

  • Related