【问题标题】:VS code displays listing directory instead of serving the html fileVS 代码显示列表目录而不是提供 html 文件
【发布时间】: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


【解决方案1】:

谢谢,我知道了。本地主机位于端口 5500 而不是 80,在代码中更改它让我获得了 html 文件。

原来是 server.listen(5500, ...)

【讨论】:

    猜你喜欢
    • 2018-03-15
    • 2019-04-01
    • 2014-06-12
    • 1970-01-01
    • 2018-03-11
    • 2020-02-25
    • 2014-02-05
    • 1970-01-01
    • 2015-08-25
    相关资源
    最近更新 更多