NicT NicT - 3 months ago 13
Javascript Question

NodeJS difficulty serving static content with Express.js

I ran a simple NodeJS and Express server on my Windows 10 development machine

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

app.use(express.static('app'));
app.use('/bower_components', express.static('bower_components'));

app.listen(3000, function () {
console.log("Listening on :3000");
});


This works, however when I tried to upload it on my Linux (Ubuntu 14.04) box, only files which are present directly under
/app
will get served, and nothing from the subfolders.

On the linux machine, I noticed I was running node version
v0.10
so I updated to
v4.5.0
. My windows machine runs
v4.4.4
.

I had an idea it might be related to permissions, so I tried setting those, but to no avail.

The file structure looks like this

├───api
├───app
│ ├───assets
│ │ ├───css
│ │ └───images
│ └───scripts
│ ├───auth
│ ├───directives
│ ├───filters
│ ├───home
│ ├───i18n
│ └───services
├───bower_components


Have anyone been through the same sort of issue?

Answer

I think you put everything in files good, so only issue, that can be painfull for nodeJS serving like you want is that path is not specified.

https://expressjs.com/en/starter/static-files.html

If you do app.use(express.static('app')); the dierectory app is injected at / directory (or execution folder of nodeJs installation in extreme case). The only thing that comes to my mind is to add __dirname + '/app' before express.static: app.use(__dirname + '/app', express.static('app'));

__dirname is a nodeJS variable in the module's scope that contains the name of the directory that the currently executing script resides in


If that is changing something try this to match everything: What is the difference between __dirname and ./ in node.js?