node.js - Express 中间件的 ENOENT : no such file or directory, stat 错误

标签 node.js express path response webstorm

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

-node_modules
-public
    -css
    -js
    control_panel.html
    index.html
app.js
packages.json

enter image description here

我在 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');
});

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

是什么导致了这个问题?

最佳答案

根据您的情况提出一些相关要点:

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

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

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

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

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

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

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

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

server
    app.js
    public
        index.html
        control_panel.html

并且,像这样的 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);

关于node.js - Express 中间件的 ENOENT : no such file or directory, stat 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39492259/

相关文章:

javascript - 如何训练 LSTM 在 tensorflow.js 中对垃圾邮件进行分类?

html - polymer 数据变化不反射(reflect)

javascript - 子属性(子集合)上的 firestore orderby

javascript - 在javascript中跳过周六和周日并将非重复条目添加到mysql数据库

mysql - 为什么受影响的行在更新/删除成功时返回 0?

node.js - 后端如何结合react-router和passport有效保护路由

javascript - 使用 Javascript 连接到 Node/Express 路由

python - AWS CDK Lambda 函数无法在路径中找到 Assets

python - 如何使用 WSGI 实现 Flask 应用按路径调度?

ios - 如何修复 Xcode 路径错误