简体   繁体   English

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

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

I have a Node.js webserver and I am fetching data from a mysql Server.我有一个 Node.js 网络服务器,我正在从 mysql 服务器获取数据。 The fetched Data needs to be displayed now in the frontend as HTML.获取的数据现在需要以 HTML 的形式显示在前端。 I am not allowed to use any 3rd Party node.js/JavaScript framework's.我不允许使用任何 3rd Party node.js/JavaScript 框架。

I'm new to Webserver development and i'm having a hard time figuring out how to "transport" the Backend Data to the Frontend.我是 Web 服务器开发的新手,我很难弄清楚如何将后端数据“传输”到前端。

I have 2 Ideas in my mind but dont know what's the right way to approach this problem...我有两个想法,但不知道解决这个问题的正确方法是什么......

  1. Send Data via JSON to Client and process it with JavaScript.通过 JSON 将数据发送到客户端并使用 JavaScript 进行处理。 (Possible? and if yes how?) (可能?如果是,如何?)

  2. Before sending the HTTP response, parse the HTML and insert the data.在发送 HTTP 响应之前,解析 HTML 并插入数据。 (Complicated without using Frameworks and too costly ?) (不使用框架很复杂,而且成本太高?)

What would be the right way to solve this problem ?解决这个问题的正确方法是什么?

Any Help would be appreciated.任何帮助将不胜感激。 Thank's.谢谢。

Solved it like this:是这样解决的:

app.js应用程序.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索引.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>

Something like this?像这样的东西?

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}/`);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM