简体   繁体   中英

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;

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

I'm then serving index.ejs, which contains the following snippet;

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

However, this always results in a 404 being returned on the image itself.

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.

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?

Note that my Dev env is 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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