我正在尝试从 URL 中获取 innerHTML
元素,并且我正在使用以下代码:
var getHTML = function (url, callback) {
if (!window.XMLHttpRequest) return;
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (callback && typeof(callback) === 'function') {
callback(this.responseXML);
}
}
xhr.open('GET', url);
xhr.responseType = 'document';
xhr.send();
}
getHTML('http://www.example.com/page', (response) => {
var pageContents = document.querySelector(root).innerHTML;
})
运行程序时,出现以下错误:
if (!window.XMLHttpRequest) return;
^
ReferenceError: window is not defined
我该如何解决这个问题?
最佳答案
好的,您正在使用 Node.js。 Node.js 没有任何称为窗口的东西,因为浏览器 javascript 上下文中的窗口就是浏览器窗口。
Node.js 没有它,因为它在服务器上运行,要通过 node.js 发出 http 请求,您可以使用以下模块:
- > node-fetch
- > axios
- > request
只需执行 npm install [modulename] 即可安装它们。你可以在 npmjs.org 找到它们的文档
关于javascript - 从 URL 返回 innerHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48127570/