0

How can I output the rows(docs) as html table format without using express/view engine. I tried writing res.write(${documents}) which is not working. Please check the following code.

const http = require('http');
const MongoClient = require('mongodb').MongoClient;

const hostname = '127.0.0.1';
const port = 3000;
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, { useNewUrlParser: true });
var documents;
client.connect(err => {
  const collection = client.db("mydb").collection("messages");
  collection.find({}).toArray(function(err, docs) {
    console.log("Found the following records");
    console.log(docs); // How can write this docs as html table
    documents = docs; // Is there any workaround for this?
  });
  client.close();
});

const server = http.createServer((req,res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.write(`Server running at http://${hostname}:${port}/. Records:${documents}`); //this document not appearing
  res.end();
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
3
  • You need to generate HTML markup from JSON or map JSON to HTML right ? Commented Mar 18, 2019 at 11:03
  • If so then try this let myObj txt += "<table border='1'>" for (x in myObj) { txt += "<tr><td>" + myObj[x].name + "</td></tr>"; } txt += "</table>" document = txt; Commented Mar 18, 2019 at 11:05
  • leme know if scope of question is different Commented Mar 18, 2019 at 11:06

2 Answers 2

1

One problem with your code is with Headers

res.setHeader('Content-Type', 'text/plain');

you need to set content-type text/html

If you want to map JSON to HTML try this

let myObj
txt += "<table border='1'>"
for (x in myObj) { txt += "<tr><td>" + myObj[x].name + "</td></tr>"; } 
txt += "</table>" 
document = txt;
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Azeen, thanks for your prompt response. I have copy pasted your code. but the output says "undefined". could you please properly format the code and suggest me how to output in res.write()? Thanks.
Hi Azeen, I corrected the format. now it finally worked. Thanks.
0

For your comment on

// How can write this docs as html table

Have you tried console.table() instead of console.log()?

1 Comment

Hi, thanks for your response. console.table() outputted nicely. i want to output such table in browser markup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.