NicT NicT - 1 year ago 109
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('/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
will get served, and nothing from the subfolders.

On the linux machine, I noticed I was running node version
so I updated to
. My windows machine runs

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

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

Have anyone been through the same sort of issue?

Answer Source

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.

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download