简体   繁体   English

如何将信息从node.js传递到html

[英]How to pass information from node.js to html

I am building a website in HTML, and I also have a node.js process running that will grab data from an npm package called better-sqlite3 . 我正在用HTML构建网站,并且我还运行着一个node.js进程,该进程将从一个名为Better better-sqlite3的npm包中获取数据。 I want to take that data, and show it on my website. 我想获取这些数据,并将其显示在我的网站上。

I am not exactly sure how to go about pushing the data over. 我不确定如何继续推送数据。 I know how to spin up a server through the http module, but I do not know how to make it push the data to the site. 我知道如何通过http模块启动服务器,但是我不知道如何使服务器将数据推送到站点。 I want this data- 我想要这个数据

{ name: 'xxxxxx', value: '15324 points (level 24)' } { name: 'yyyyyy', value: '9643 points (level 19)' } {名称:'xxxxxx',值:'15324点(24级)'} {名称:'yyyyyy',值:'9643点(19级)'}

Displayed on the site, and hopefully fit my design. 显示在网站上,并希望适合我的设计。

Any tips y'all can give me? 你们都可以给我什么提示吗? Thanks ahead of time. 提前谢谢。

You cannot do this directly in HTML(it is mostly used for the layout of a webpage), you need some client side Javascript as well that connects to the server written in NodeJs. 您不能直接在HTML中执行此操作(它主要用于网页布局),还需要一些客户端Javascript来连接到用NodeJs编写的服务器。 The communication is done through http protocol. 通过http协议进行通信。 The server exposes a RestApi and returns the object you specified to the browser where it is rendered. 服务器公开RestApi,并将您指定的对象返回到呈现该对象的浏览器。

I guess you want to use AJAX to get all the data you need. 我想您想使用AJAX来获取所需的所有数据。 This is your server. 这是您的服务器。 (I'm using express, but you can do this without it) (我正在使用快递,但没有它您可以这样做)

var express = require("express");
var app = express();

//Just a setting for enable CORS (Cross-origin resource sharing )
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

//creating your object
var obj = { 
    name: 'xxxxxx', 
    value: '15324 points (level 24)'
}

//sending your object
app.get("/obj", function(req, res){
    res.json(obj);
});

app.listen("3002", function(){
    console.log("Server is Running");
});

And this is your HTML file with the AJAX request: 这是带有AJAX请求的HTML文件:

<!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
        <div id="objPanel"></div>
        <script type="text/javascript">
          var xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
              document.getElementById("objPanel").innerHTML = this.responseText;
            }
          };
          xhttp.open("GET", "http://localhost:3002/obj", true);
          xhttp.send();
        </script>

    </body>
    </html>

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

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