The way you're using express.static
isn't right. You shouldn't pass it a single file to return, that's sendFile
. express.static
is used to serve up a entire directory and should be called outside the get
handler.
For example, this would serve up a directory called public
at the root of your URL. Any requests for files that aren't found would be passed on through the middleware/router chain to the next handler:
app.use(express.static(path.join(__dirname, 'public')));
Importantly this should appear before your calls to app.get
, app.post
, etc. and not inside a handler.
So if you've got a file at public/myfile.html
that would be served up at http://localhost:3000/myfile.html
, where I've assumed your server is at localhost:3000
. If you wanted to add an extra section of path to the URL, e.g. http://localhost:3000/stat/myfile.html
that would be:
app.use('/stat', express.static(path.join(__dirname, 'public')));
If you wanted to serve up a single file then you could use sendFile
, a bit like this:
app.get('/myfile.html', function(req, res) {
res.sendFile(path.join(__dirname, '/myfile.html'));
});
Note that this is singling out a particular file so any resources such as CSS would need to be handled separately. If the HTML, CSS, etc. are all in the same folder it would make sense to use express.static
to serve up the entire directory instead.
It is also worth noting that express.static
has a setting called index
that defaults to serving up a file called index.html
if a request comes in for '/'.
Further reading: