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>")