-2

enter image description hereWhy after installing node.js, an error like that occurs after I run the code of various javascript commands, it seems it's not because the code is an error but because node.js doesn't want to connect to the server.

enter image description hereWhen I tried to check whether node.js was connected to localhost or not, it turned out it wasn't connected, so how do I get node.js to connect to 127.0.0.1:300?

3
  • Welcome to Stack Overflow! Please take the tour, have a look around, and read through the help center, in particular How do I ask a good question? Please post code, error messages, console output, markup, data, data structures, and other textual information as text, not just as a picture of text. Why: meta.stackoverflow.com/q/285551/157247 Commented Jan 13, 2024 at 13:29
  • 2
    document is a predefined global on browsers. The Node.js environment doesn't have that global, because it's not a browser. Commented Jan 13, 2024 at 13:30
  • Looking at the image of code, it seems you are using vanilla js with HTML and CSS. You can install Live Server extension in VS Code and run index.html using Live Server. It will open index.html file in browser. If index.js file connected to index.html file then you will see value of x in browser console. Commented Jan 13, 2024 at 13:49

1 Answer 1

0

You are running your JavaScript file in node.js enviroment. The document object and its methods, like getElementById in your case, are part of the Web API provided by browsers for manipulating web pages and are not available in Node.js.

Why? Because, node.js is a JS runtime used primarily for server-side scripting and does not have a built-in Document Object Model (DOM) like a web browser does

You can read more about the Document interface here: Document API

To run your js script in the browser, add it as a script in your index.html file with the <script> tag. This will load your javascript when your HTML file is loaded in the browser. You can follow the steps mentioned here:

Use JavaScript within a webpage

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.