Node.js: How to extract database information and display in HTML pages

Asked

Viewed 1,126 times

1

I have learned how to fetch information from Mysql database, but I cannot manipulate this data to expose in HTML pages. The code I’m going to expose underneath I got from w3school:

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});

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

Pay attention to the part where I take the data, it is stored in the result variable, only you can not manipulate this information outside the scope of the function. How do I take this data and place the result on an HTML page? Is it possible to do this without a framework? If not, which framework to use?

  • You can do it by hand with http modules or use express (which is what most do)

  • When I extract the information, it gets stuck in the context of the function. How do I export this data to other modules?

  • You need to create and export a function that executes the query and returns the result. Give a look in that question I think it’ll help you

1 answer

1

Callbacks:

The data cannot go outside the scope of this function since it represents a callback, that is, it is not executed in code order, but is called only when data is loaded from the database.

To learn more about callbacks, suggest reading that question.

Choose to use an existing framework:

To facilitate this process, many developers choose to use frameworks. Below I will quote you in my order of preference:

  1. Adonisjs, a MVC framework, similar to Laravel and Ruby on Rails;
  2. Expressjs, a minimalist framework for Node.JS;
  3. Hapi.js, still minimalist, but with some more features than Express.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.