Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`express.static()` keeps routing my files from the route

While working on an express project, I am trying to use an express.Router object to handle my application routes. In my main app file, I have added a static route for all my static files(css, javascript, html).

app.js

var express = require('express');
var io = require('socket.io')(app);
var bodyParser = require('body-parser');
var router = require('./include/router');

var app = express();
app.use('/', router);
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());

io.on('connection', function(socket) {

});

app.listen(3000);

router.js

var express = require('express');
var path = require('path');

var router = express.Router();

router.get('/', function(req, res) {
  res.sendFile('/html/index.html');
});

module.exports = router;

When I try to access localhost:3000 I get a 404 showing Error: ENOENT, stat 'C:\html\index.html'

Furthermore, when I try to access the static route directly(http://localhost:300/html/index.html I believe), but that gives me Cannot GET /html/index.html.

This is the tree of my public folder

public
├───css
├───hmtl
|   └───index.html
├───img
└───js

Am I routing this wrong? How can I fix it?

like image 757
James Parsons Avatar asked Jan 26 '15 00:01

James Parsons


People also ask

Can express serve static files?

To serve static files such as images, CSS files, and JavaScript files, use the express. static built-in middleware function in Express. The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express.

Why is the static route not functioning as intended?

Why is the static route not functioning as intended? The network mask is incorrectly configured. The next hop neighbor IP address is not configured. The destination network is incorrectly configured.


1 Answers

You must inverse the order of your router

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

means your router will be called first and, if no middleware handles the request, then express will call static files so, if you put the static middleware first, the express will handle static files first.

It is also recommended to put static middleware first.

For your problem you should try this:

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

Express will try static files first on public/html folder, then on the rest (including the public/html), i prefer putting html files on the root of public folder or maybe on a different folder (e.g public-html, static-html)

like image 79
Sergio Marcelino Avatar answered Oct 20 '22 03:10

Sergio Marcelino