drizo drizo - 1 year ago 103
CSS Question

NODEJS and HEROKU : I can't serve the static files once the server is deployed

ok, I have the simple server which is the following setup:

var port = process.env.PORT || 8080;

var server = http.createServer(app).listen(port);

process.env.PWD = process.cwd();


app.get('/',function(req,res) {

res.sendfile(process.env.PWD+ '/index.html');


I create a git in the folder and I successfully push it to heroku, but when I open it I get this result:


If you open the console log you will see that it fails to load css and js static files which can't be found,although when I test my app locally this setup works and the files are served as planned.

What am I doing wrong?

P.S. I don't think it a problem with heroku,I believe the problem is within nodejs and uploading the app.

Answer Source

I'm going to guess that the problem lies in how you're specifying the directory for static files.

What I normally see -- and prefer -- is setting up static this way:

app.use(express.static(__dirname + '/public'));

That means Express will look for the static files in the public subdirectory of the same directory that your application file is in. Let's imagine you have two apps, app1.js and app2.js. app1.js is configured the way you have it, using process.cwd() (current working directory), and app2.js is using __dirname as its base. Both of these apps are in /home/drizo/app.

If you do this, both will work correctly:

cd /home/drizo/app
node app1.js              # uses cwd + /public = /home/drizo/app/public
node app2.js              # uses __dirname + /public = /home/drizo/app/public

However, if you do it like this:

cd /home/drizo           # or ANY directory that's not /home/drizo/app
node app/app1.js             # uses cwd + /public = /home/drizo/public - WRONG
node app/app2.js             # uses __dirname + /public = /home/drizo/app/public

As you can see, app1.js is using the directory that the app was started from. I'm not sure how Heroku starts/restarts apps, but I'm guessing it isn't doing it from the directory you expect.

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