Reputation: 23
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
. 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.
I want this data-
{ name: 'xxxxxx', value: '15324 points (level 24)' } { name: 'yyyyyy', value: '9643 points (level 19)' }
Displayed on the site, and hopefully fit my design.
Any tips y'all can give me? Thanks ahead of time.
Upvotes: 1
Views: 1169
Reputation: 97
I guess you want to use AJAX to get all the data you need. 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:
<!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>
Upvotes: 1
Reputation: 1123
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. The communication is done through http protocol. The server exposes a RestApi and returns the object you specified to the browser where it is rendered.
Upvotes: 1