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

标签 javascript html mysql node.js fetch

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

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

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

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

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

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

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

最佳答案

这样解决:

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>

关于javascript - 从 Node.js(无框架)在网站上显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44421120/

相关文章:

javascript - 按类别选择标题元素

javascript - jQuery 向右滑动 - 并替换 HTML

php - 拉维尔 : highest id used in a column

javascript - 用jsp更新数据库

javascript - 如何根据子属性将 JSON 排序到数组中

javascript - 通过 Ratchet (Push.js) 使用缓存页面

html - 需要帮助将 "button"添加到 div 的右侧

php - 如果变量存储为 varchar,是否可以将其识别为 int 或 float 或 time

php - MySQL 查询 : JOIN multiple tables with ORDER BY

javascript - 如何使用 Vanilla JS 构建自己的 WYSIWYG 编辑器 (RTE)