Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a JSON dataset as a table with Node.js and Express

First of all, I would like to point out that I'm very new to Node.JS. I'm trying to use NodeJS to make a page containing multiple tables and info. My problem is, that I can't get the result from the SQL query into an HTML table. Currently I .send the data into an HTML page using express.

Code that I use:

    var http = require('http');
    http.createServer(function(req, res) {});
      var mysql = require("mysql"); 
      var express = require('express');
      var app = express();
      console.log('Creating the http server');
      con.query('SELECT id ,name FROM customer', function(err, rows, fields)
    {
        console.log('Connection result error '+err);
        console.log('num of records is '+rows.length);

        app.get('/', function (req, res) {
          res.send(rows);
        });

    });

    app.listen(3002, function () {
      console.log('Example app listening on port 3000!');
    })

This prints all the data from my sql statement on my HTML page:

{"id":"1","name":"Robert"}
{"id":"2","name":"John"}
{"id":"3","name":"Jack"}
{"id":"4","name":"Will"}

what I would like to have as result is :

id              Name
1               Robert
2               John
3               Jack
4               Will
..etc 

Is this even possible to do in Node JS?

like image 435
Rahul Sharma Avatar asked Jan 15 '16 11:01

Rahul Sharma


2 Answers

Similar to Jade you could use Embedded JS

<table>
  <tr>
    <th>id</th><th>Name</th>
  </tr>

  <% for (var i = 0; i < data.length; i++) { %>
    <tr>
      <td><%= data[i].id %></td>
      <td><%= data[i].name %></td>
    </tr>    
  <% } %>
</table>

This would iterate through an array of objects (which I have saved as data and populate a table based on that.

like image 57
Simon Legg Avatar answered Oct 11 '22 14:10

Simon Legg


I would recommend you look at Jade. It is a template engine for node js which can be used to create html pages. It is easy to use and very flexible.

A good tutorial is found here. It shows you how to create a simple Website with Node, Express and Jade and is a good starting Point in my opinion.

To solve your problem with Jade there are several answers in stackoverflow like here.

like image 2
Urknecht Avatar answered Oct 11 '22 12:10

Urknecht