如何在不使用express / view引擎的情况下将行(docs)输出为html表格式。我尝试编写无法正常工作的res.write(${documents}
)。请检查以下代码。
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}/`);
});
答案 0 :(得分:1)
您的代码的一个问题是标题
res.setHeader('Content-Type', 'text/plain');
您需要设置内容类型text/html
如果要将JSON映射到HTML,请尝试
let myObj
txt += "<table border='1'>"
for (x in myObj) { txt += "<tr><td>" + myObj[x].name + "</td></tr>"; }
txt += "</table>"
document = txt;
答案 1 :(得分:0)
对于您的评论
//如何将该文档写为html表
您是否尝试过使用console.table()而不是console.log()?