Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get app.css, main.js, other files to load using an Express server

I have the following code:

var express = require('express');
var app = express();
var server = require('http').Server(app);

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

server.listen(3000);

However, only my index.html page displays, and I have a GET error for my other files. When I load index.html at localhost:3000, I have errors in the console with trying to find my main.js and app.css files. Even when I include my other files as a src in the html file, they are not able to load. I think this may be because I am only sending the single html file to the server. How can I handle this so that all of the relevant files are sent to the server?

like image 411
Nick Mandel Avatar asked Dec 25 '22 00:12

Nick Mandel


1 Answers

Using

res.sendfile(__dirname + '/index.html');

in response to a get request won't serve up all your static files, only the individual index.html file — meaning your css and javascript files will not be found by your server (even when you link to them in your html).

You need to use the included express static middleware (the only included middleware in express v4).

If your static files are in the same directory as your server.js file then add

app.use(express.static('.'));

This serves up all of your local static files and makes them accessible on your server.

I wrote a blog post on this a while back:

https://medium.com/@willsentance/how-to-avoid-main-js-style-css-not-found-or-how-i-learned-to-love-serving-static-files-with-node-2121255da0fd

like image 200
javascriptttt Avatar answered Jan 27 '23 05:01

javascriptttt