FakeRune
FakeRune

Reputation: 63

Other ways to connect and display mysql with node.js through html

Hey I'm trying to learn how to use node.js with mysql. I'm at the point where I can display data from mysql in the browser. I was wondering if there is another way (smarter way) to do this than what I've have done so far.

To be more specific i'm looking for a different way to process the data other than Jquery which I use in my index.html. I would rather avoid Jquery all together. Of course only if this is not the optinal way to go about this.

I had seen some using sendFile, but I can't seem to get it to work at all probably because I don't know how to process it on the html side.

this is my app.js

// moduels
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-Parser')
var urlencodedParser = bodyParser.urlencoded({ extended: false });

// sends data to html side 
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', express.static(__dirname + '/'));
app.set('view engine', 'html');

// connect to database
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "1234",
    database: "BathBombs_DB"
});

con.connect();

// routes
app.get('/api', function(request, response){
    console.log('GET request received at /') 
    con.query("SELECT * FROM customers", function (err, result) {
        if (err) throw err;
        else{
            response.json(result);
            //response.sendFile(__dirname + "/index.html");
        }

    });
});

// listen for trafic and display on localhost:9000
app.listen(9000, function () {
    console.log('Connected to port 9000');
});

and this is my index.html.

  <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <title>Document</title>
  </head>
  <body>

     <table id="table">
       <tr>
         <td></td>
       </tr>
     </table>

  <script>

    $(document).ready(function(){

      $.get("http://localhost:9000/api", function(data){
        var html = '';
        for (var i = 0; i < data.length; i++) {  
          html += '<tr><td>' + data[i].id + '</td><td>'   
          html += '<tr><td>' + data[i].firstname + '</td><td>'
          html += '<tr><td>' + data[i].lastname + '</td><td>'
          html += '<tr><td>' + data[i].address + '</td><td>'
          html += '<tr><td>' + data[i].postal_code + '</td><td>'
          html += '<tr><td>' + data[i].city + '</td><td>'
          html += '<tr><td>' + data[i].country + '</td><td>'
          html += '<tr><td>' + data[i].email + '</td><td>'
          html += '<tr><td>' + data[i].tlf + '</td><td>'        
        }
        $('#table').empty().append(html);
      });
    });

  </script>

  </body>
  </html>

Upvotes: 0

Views: 62

Answers (1)

Momo
Momo

Reputation: 368

You're looking for the modern Fetch API. How to use it.

You already have your route set up which will process all HTTP GET requests to /api, so you can have a function like so:

async function getData(url = '') {
    const response = await fetch(url, {
        method: 'GET',
    });

    return response.json();
}

And you can call it:

const url = '/api';
const response = getData(url);

response.then((items) => {        
    // construct your table nodes here
});

You're probably going to get confused about the usage of async and await, but it's good to know them if you want to work with the Fetch API, since a call to fetch returns a promise.

Upvotes: 1

Related Questions