【发布时间】:2020-07-15 15:14:15
【问题描述】:
我想按照我通过 Youtube 教程学到的代码通过 nodejs 提供 Disp.html 文件。
const http = require("http");
const fs = require("fs");
const fileContent = fs.readFileSync("Disp.html");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-type": "text/html" });
res.end(fileContent);
});
server.listen(80, "127.0.0.1", () => {
console.log("Listening on port 80");
});
我在 VS Code 中创建了一个文件夹,其中 app.js 和 Disp.html 作为文件。每次我运行代码时,它都会显示列表目录来代替我希望查看的 HTML 内容。
我该怎么做才能得到预期的结果?
【问题讨论】:
-
您运行它的方式有问题。 听起来您可能正在运行 VS Code 实时服务器并访问它,而不是运行您在上述代码中编写的服务器。
-
好像你在 www 目录之外获得了这个文件,启动节点应用程序并在公共目录中拥有正确的文件,或者它的名字适合你。
-
请注意,直接与
http.createServer打交道几乎总是比您花费的时间更烦人,而且您通常最好使用 Express.js。 -
@PatricNox — 不。没有
www目录,因为这不是 Apache/IIS/whatever。如果Disp.html位于错误的位置,则尝试读取它会出错。
标签: javascript html node.js express web-development-server