ReferenceError:文档不是仅在Vscode编辑器中定义 [英] ReferenceError: document is not defined only in Vscode editor
本文介绍了ReferenceError:文档不是仅在Vscode编辑器中定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此错误不会消失!它只显示在VScode输出控制台中,我在Google Chrome中运行代码,错误就消失了。
ReferenceError:未定义文档
示例: https://codepen.io/Dany2020/pen/vYLWPox
`[Running] node "c:\index.js"
var headerText = document.getElementById("header");
^
ReferenceError: document is not defined
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
[Done] exited with code=1 in 0.132 seconds`
推荐答案
我在Google Chrome中运行代码,错误消失了。
这里的区别在于您运行代码的环境。Web浏览器和Node.js都可以使用JavaScript作为一种语言,但它们运行代码的上下文非常不同。您正尝试在Node.js:
中运行代码[Running] node "c:\index.js"
确实在Node.js中没有默认的document
对象。在浏览器中有,因为在浏览器的上下文中,您正在查看文档(网页)。但在Node.js的上下文中并非如此。这也意味着您正在使用的代码行在Node.js:
var headerText = document.getElementById("header");
如果没有网页,您正在查看的是什么文档?你想要的是什么元素?这些东西都不存在。
听起来您正在编写的代码应该在网页上作为浏览器内的JavaScript执行。所以这就是你应该运行它的地方。代码将位于该网页的HTML中的<script>
元素中(或位于由<script>
元素引用的单独文件中)。如果Node进程是您的服务器,则只在那里执行服务器端逻辑。服务器返回的网页将包含您在问题中引用的代码。
这篇关于ReferenceError:文档不是仅在Vscode编辑器中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文