ENOENT:没有这样的文件或目录,Express Middleware 出现错误

1 response path node.js express webstorm

这似乎是文件路径的常见错误,但我的问题更奇怪,因为代码昨天工作正常,但今天不行(而且我没有更改任何代码)。我的文件夹目录很简单:

-node_modules
-public
    -css
    -js
    control_panel.html
    index.html
app.js
packages.json
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我在 app.js 中使用 Express 中间件来帮助渲染文件。

var express = require("express");
var app = express();

app.use(express.static("public"));

app.get('/', function get(req, res) {
    res.sendFile('/index.html');
});

app.get('/control_panel', function get(req, res) {
    res.sendFile('/control_panel.html');
});
Run Code Online (Sandbox Code Playgroud)

当我尝试在浏览器中打开index.html时,没有问题,一切都按预期进行。然而,当我尝试在浏览器中打开 control_panel.html 时,我得到Error: ENOENT: no such file or directory, stat '/control_panel.html' at Error (native)

是什么导致了这个问题?

jfr*_*d00 5

根据您的情况,有一些相关要点:

  1. 所有静态资源(html 文件、图像、CSS 文件、客户端脚本文件等)都应使用适当的express.static(...)语句自动提供服务。您不应该为静态资源创建单独的路由。

  2. 为了使其express.static()正常工作,您必须在仅包含公开文件的目录层次结构中找到所有静态资源。

  3. 您的私有服务器端文件(例如)app.js不应位于该公共目录层次结构中。他们应该在别处。

  4. 您的路径express.static()不正确。

  5. 您的路径res.sendFile()不正确。

我建议您采取以下措施来解决问题:

  1. 将 app.js 从该public目录中移出。它需要位于私有目录中。我建议该public目录是 app.js 所在位置的子目录。
  2. 然后,您的express.static()inapp.js将工作属性为您的静态 HTML 字段提供服务。
  3. index.html然后,您可以删除为和control_panel.html因为express.static()应该为它们提供服务的两条路线。

这是一种可行的层次结构:

server
    app.js
    public
        index.html
        control_panel.html
Run Code Online (Sandbox Code Playgroud)

并且,像这样的 app.js:

var express = require("express");
var app = express();

// serve static files found in the public sub-directory automatically
app.use(express.static("public")); 

app.listen(80);
Run Code Online (Sandbox Code Playgroud)