html - 关于 http-server 与在 NodeJS 中使用 http 的混淆

标签 html node.js http httpserver

我正在尝试使用 NodeJS 运行 html 文件。我安装了一个名为“http-server”的命令行 Node 包。当我使用 http-server 运行 html 文件时,它打开得很好。

当我尝试使用 NodeJS 的 html 库托管相同的 html 文件时,问题开始出现。我尝试使用下面的代码运行我的 html 文件,但它没有像我预期的那样工作。该网页只是一个空白的白页。

这是为什么? http-server 包做了哪些我的常规代码没有做的事情?

提前感谢您的帮助!

var http = require('http');
var fs = require('fs');

var html = fs.readFileSync('index.html');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(html);
}).listen(8000);

最佳答案

fs.readFileSync('index.html'); 替换为 fs.readFileSync(__dirname + '/index.html'); (__dirname 是目录项目在)

关于html - 关于 http-server 与在 NodeJS 中使用 http 的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53965461/

相关文章:

javascript - 使用 css 和图片打开新窗口

javascript - 如何从 jQuery 中的字符串中删除可变数量的 p 标签

html - 重定向到特定的 aspx 页面

javascript - 公共(public) Assets 的正则表达式路线

java - 从 HttpUrlConnection 对象获取 header

http - 如何在 Java 中安全地处理原始(文件)数据?

javascript - Node JS : Request Loop Until Status Code 200

jquery - 在具有固定高度/宽度的 div 中显示溢出字符串的底部?

javascript - 如何发送express文件夹中的一些特定的js、css?

node.js - 在 Node JS 中为 WebSocket (ws) 使用自签名 CA 证书