且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-22 21:20:20

基于您的情况的一些相关要点:

A number of relevant points based on your situation:

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

  1. All static assets (html files, images, CSS files, client-side script files, etc...) should be serviced automatically with an appropriate express.static(...) statement. You should not be creating individual routes for static resources.

要使express.static()正常运行,必须在目录层次结构中找到所有静态资源,该目录层次结构仅包含旨在公开的文件.

To make express.static() work properly, you must locate all your static resources in a directory hierarchy that contains only files meant to be public.

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

Your private server-side files such as app.js should not be in that public directory hierarchy. They should be elsewhere.

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

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

我建议您采取以下措施:

What I would suggest you do to fix things is the following:

  1. 将app.js移出public目录.它必须在私有目录中.我建议public目录是app.js所在的子目录.
  2. 然后,您在app.js中的express.static()将可以工作以提供静态HTML字段.
  3. 然后,您可以删除index.htmlcontrol_panel.html的两条路线,因为express.static()应该为它们服务.
  1. Move app.js out of the public directory. It needs to be in a private directory. I'd suggest the public directory be a sub-directory from where app.js is located.
  2. Then, your express.static() in app.js will work property to serve your static HTML fiels.
  3. Then, you can remove the two routes you have for index.html and control_panel.html because express.static() should be serving them.

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

Here's one hierarchy that would work:

server
    app.js
    public
        index.html
        control_panel.html

然后是一个像这样的app.js:

And, an app.js like this:

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);