简体   繁体   中英

How to pass data from Node.js to html

I have a simple program and some data strings that I want to pass to HTML page that hosted locally, but I'm getting error: ReferenceError: document is not defined

There's my .js file index.js:

let some_string = "some data";

document.getElementById("dataButton").onclick = function(){
    var paragraph = document.createElement("p");
    var text = document.createTextNode(some_string); 
    paragraph.appendChild(text);
    var element = document.getElementsByTagName("body")[0];
    element.appendChild(paragraph);
}

And there's my HTML test.html:

<!DOCTYPE html>
<html>

<head>
    <title>New title</title>
</head>

<body>
    <h1>Data page</h1>

    <button id="dataButton">Add data</button>
    <script src="index.js"></script>
</body>

</html>

Many thanks if someone come up with idea what am I doing wrong!

Update your files to the following

 let some_string = "some data"; const dataButton = document.getElementById("dataButton"); dataButton.addEventListener("click", () => { var paragraph = document.createElement("p"); var text = document.createTextNode(some_string); paragraph.appendChild(text); var element = document.getElementsByTagName("body")[0]; element.appendChild(paragraph); });
 <!DOCTYPE html> <html> <head> <title>New title</title> </head> <body> <h1>Data page</h1> <button id="dataButton">Add data</button> <script src="./index.js"></script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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