【问题标题】:How to get HTML file contents as a string in javascript如何在javascript中将HTML文件内容作为字符串获取
【发布时间】:2019-11-28 23:04:00
【问题描述】:

我正在尝试以字符串形式获取 JavaScript 中 HTML 文件的内容。

写了这样的代码,但是不起作用,显示错误:Error: Cannot find module 'xmlhttprequest'

我该如何修复它,或者还有其他方法可以在 JavaScript 中读取 HTML 文件吗?

function getFile(U) {
    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var X = new XMLHttpRequest();
    X.open('GET', U, false);
    X.send();
  return X.responseText;
}

const f = getFile('index.html');

const http = require('http');

http.createServer((request, response) => {
    response.writeHead(200, {'Content-Type': 'text/html'});

    response.end(f);
}).listen(80, () => {
    console.log('Server work');
});

【问题讨论】:

  • XMLHttpRequest,但您也可以使用fetch()
  • 你能发布你的代码吗?我们还应该如何在其中找到错误?
  • 请清楚说明您打算做什么。另外,分享您显示错误的代码
  • 这是一个 node.js 问题吗?如果是这样,请适当标记。
  • 您正在尝试使用仅存在于浏览器中的XMLHttpRequest。当你在 NodeJs 中时。哪个不知道XMLHttpRequest

标签: javascript html node.js


【解决方案1】:
function getFile(U) {
    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var X = new XMLHttpRequest();
    X.open('GET', U, false);
    X.send();
  return X.responseText;
}

const f = getFile('index.html');

const http = require('http');

http.createServer((request, response) => {
    response.writeHead(200, {'Content-Type': 'text/html'});

    response.end(f);
}).listen(80, () => {
    console.log('Server work');
});

【讨论】:

  • 请编辑您的问题,而不是将您的代码放在答案中。
猜你喜欢
  • 2014-07-26
  • 2014-08-09
  • 1970-01-01
  • 2013-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多