Hello! How to pull data from a database query using the connection.query function in node.js and transfer it to html? Thank you in advance. On the Internet I found an example (Does not work):

### `mysql.js` var http = require('http'); var mysql = require('mysql'); var fs = require('fs'); var connection = mysql.createConnection({ database : 'mysql', user : 'root', password : 'toor' }); var x={}; var query = function(){ connection.connect(); connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; x = rows[0].solution; }); connection.end(); }; var answer = function(){ return x; }; module.exports.query = query; module.exports.answer = answer; var server = http.createServer(function(request, response) { response.writeHead(200, {'Content-Type': 'text/html'}); var myReadStream = fs.createReadStream(__dirname + '/index.html', 'utf8'); myReadStream.pipe(response); }); server.listen(3000, '127.0.0.1'); console.log('Прослушивание порта 3000'); 

### index.html

  <!DOCTYPE html> <html> <head> <title>Hello World2!</title> <script> var mysql = require('./mysql.js'); function bodyOnLoad(){ mysql.query(); }; function getAnswer(){ document.getElementById("answer").innerHTML = mysql.answer(); } </script> </head> <body onload="bodyOnLoad();"> <div id="answer" onClick="getAnswer;">Click me</div> </body> </html> 
  • I do not see the use of nodejs in the question. Start by raising a web server on a node ... - Pavel Mayorov
  • @PavelMayorov raising the server there is just there. Like require server libraries on client :) - Dmitriy Simushev
  • @DmitriySimushev this is already after my comment added ... - Pavel Mayorov
  • help is still needed) - Blackbonny

1 answer 1

Use a templating engine and some kind of http-framework for convenience. For example, for Express and the template engine handlebars, the data transfer in html will look like this:

 router.get("/", function(res, req, next){ connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { res.render("index.hbs", data: rows} }); }) 

And then in your .hbs (read .html) document you can display

 <div id="data">{{data.yourdata}}</div> 
  • Thanks, but how can you implement without using a template engine, express? interest for the sake of) - Blackbonny
  • @Blackbonny well, it will be more complicated and will require writing more code. Well, you can create a simple api with the data, but even without the knowledge of node.js, you can’t even do this ... - Angry B
  • Thanks, I will study. - Blackbonny