在网站上显示来自 Node.js 的数据(无框架)

Displaying Data on Website from Node.js (Without Frameworks)

我有一个 Node.js 网络服务器,我正在从 mysql 服务器获取数据。获取的数据现在需要在前端显示为 HTML。我不允许使用任何第 3 方节点。js/JavaScript 框架的。

我是网络服务器开发的新手,我很难弄清楚如何将后端数据“传输”到前端。

我有 2 个想法,但不知道解决这个问题的正确方法是什么...

  1. 通过JSON向客户端发送数据并用JavaScript处理。 (可能吗?如果是怎么办?)

  2. 在发送 HTTP 响应之前,解析 HTML 并插入数据。 (不使用框架很复杂,而且成本太高?)

解决这个问题的正确方法是什么?

任何帮助将不胜感激。谢谢

是这样的吗?

const http = require('http');
const util = require('util');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  mysql.query("select * from table").then(rows => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end(`<html><head></head><body>${util.inspect(rows)}</body></html>`);
  })
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

这样解决的:

app.js

var http = require('http');  
var url = require('url');

var server = http.createServer(function(req, res) {
    var q = url.parse(req.url, true);
    if(q.filename == "command"){
        res.writeHead(200, {'Content-Type':'application/json'});
        return res.end(some_json);
    }
}

index.html

<script>
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST","http://localhost:8000/command", true);
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            //Process Data
            var jsonObj = JSON.parse(xmlhttp.responseText);
            document.getElementById("test").innerHTML = jsonObj;
        }
    }
    xmlhttp.send();
</script>

<div id="test"></div>