Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs Index.html Loads but Links & Scripts 404

I have a nodejs server running with the client side encapsulated in a client folder to make managing the folder structure for index.html easy. Then the links and scripts should load no problem.

client folder
  /index.html
  /style.css
  /script.js
closer folder
  /closure
  /etc. 
app.js
package.json
utility.js

In my app.js file I have a normal

app.get ('/', function (req,res) {
res.render('index.html');
});

and when I run and go to the local host port the file loads, but when I open the chrome console, I see that the index.html file failed to load any of the scripts with a 404 error not found. I notice that in a lot of express apps there seems to be a common pattern of something along the lines of

this app.set('views', __dirname + '/client');

this app.use(express.static(__dirname + "./client"));

this app.use('client', express.directory('client'));

but I don't see an explanation on the difference between app.use and app.set, nor a good explanation, the best the I could find was

app.set('views', __dirname + '/views'): Use ./views as the default path for the client-side templates

from Alex Young's article but even this was a little sparse and dry for me, I'm hoping for a bit deeper of an explanation as to why the index file might be unable to load a link on the same directory level as it.

<link rel="stylesheet" type="text/css" href="style.css" />

I look at this and I can't find the problem.

like image 963
mibbit Avatar asked Apr 09 '14 21:04

mibbit


1 Answers

From the answer Express-js can't GET my static files, why? I'd suggest:

app.use("/client", express.static(__dirname + '/client'));

This is needed because your:

app.get ('/', function (req,res) {
res.render('index.html');
});

is only addressing what happens when someone goes to / and saying that index.html should be served. That alone doesn't serve anything else.

like image 172
Jason Aller Avatar answered Nov 15 '22 09:11

Jason Aller