简体   繁体   English

express.js静态无法识别已定义的“公用”文件夹

[英]express.js static not recognising defined 'public' folder

I have the following dir setup; 我有以下目录设置;

**app** **controllers** *index.server.controller.js* **models** **routes** *index.server.routes.js* **views** *index.ejs* **config** **env** *config.js* *express.js* **public** **css** **img** *logo.jpg* **js** *server.js* *package.json*

Inside express.js, I'm loading the static directory using the following; 在express.js内部,我使用以下命令加载静态目录;

//app.use(express.static(__dirname + '\\..\\public\\') - also attempted
app.use(express.static('./public'));

I'm then serving index.ejs, which contains the following snippet; 然后,我要提供index.ejs,其中包含以下代码段;

<img src="img/logo.jpg" alt="Logo"/>

However, this always results in a 404 being returned on the image itself. 但是,这总是导致在图像本身上返回404。

C:\\nodejs>node horizontal/server Localhost running on port 3000 GET / 304 13.763 ms - - GET /img/logo.jpg 404 4.372 ms - 25

As seen above, I've attempted giving a strict __dirname path (as I had to do with setting up the path to views, as seen below) - and also attempted just inserting public/img/logo.jpg in order to see it getting served up. 如上所示,我尝试提供严格的__dirname路径(就像我必须设置视图的路径一样,如下所示)-并且还尝试仅插入public / img / logo.jpg才能看到它服役。

Views, as it works; 视图,因为它起作用;

app.set('views', __dirname+'\\\\..\\\\\\\\app\\\\views\\\\'); app.set('view engine', 'ejs');

Would anyone have any ideas as to why express isn't seeing the public folder, or serving static content from it? 是否有人对为什么express无法看到公用文件夹或从中提供静态内容有任何想法?

Note that my Dev env is Windows8.1. 请注意,我的开发环境是Windows8.1。

You should use the path module to do that. 您应该使用路径模块来执行此操作。

var path = require('path');

With an app directory looking like below 应用目录如下所示

在此处输入图片说明

You would just access the public folder like this: 您只需要像这样访问公用文件夹:

app.use(express.static(path.join(__dirname, 'public')));

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM