Display a JSON Dataset as a Table with Node.js and Express

First of all, I would like to note that I am very new to Node.JS. I am trying to use NodeJS to create a page containing several tables and information. My problem is that I cannot get the result of an SQL query into an HTML table. I am .send data to an HTML page using express.

The code I'm using is:

  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 outputs all the data from my sql statement in my HTML page:

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

what I would like to get as a result:

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

Is it possible to do this in Node JS?

+5
source share
2 answers

I would recommend you see Jade . This is a template engine for node js that you can use to create html pages. It is easy to use and very flexible.

Good guide found here . It shows you how to create a simple website using Node, Express and Jade and, in my opinion, is a good starting point.

To solve your problem with Jade, there are several answers in stackoverflow, for example.

+2
source

Like Jade, you can 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 will lead to going through an array of objects (which I saved as data and populated a table based on this.

+3
source

Source: https://habr.com/ru/post/1240683/


All Articles