Fetching data in Node.js

Fetch is a significant process which has a great impact on the performance and behaviour of web sites . Retrieving individual data items from the server to update sections of the web page is the process performed in a data fetch. In this blog we will see how to fetch data from a MySQL database to Node.js. Assuming you already have a table in your database. Let’s name the database ‘test’ and the table as ‘users’. Now connect the database to your project.

const mysql = require('mysql2');

const db_connection = mysql.createPool({

    host: 'localhost',

    user: 'root',

    database: 'test',

    password:'your_db_password'

});

Now the only job left is to fetch the database. Using db_connection we execute the select query to fetch data from the database and display on our page.

db_connection.promise()

.execute("SELECT * FROM `users`")

.then(([rows]) => {

    // show the first user name

    console.log(rows[0].name);

    // show the all users name

    rows.forEach(user => {

        console.log(user.name);

    });

}).catch(err => {

    console.log(err);

});