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

While working on an express project, I am trying to use the express.Router object to process the routes of my application. In my main application file, I 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 message showing Error: ENOENT, stat 'C:\html\index.html'

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

This is my public folder tree

  public
 β”œβ”€β”€β”€css
 β”œβ”€β”€β”€hmtl
 |  └───index.html
 β”œβ”€β”€β”€img
 └───js

Am I laying it wrong? How can i fix this?

+7
express static-files
source share
1 answer

You must invert your router order

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

means that your router will be called first, and if no middleware processes the request, then the expression will call static files, so if you install static middleware first, express will process the static files first.

It is also recommended that you install static middleware first.

For your problem you should try the following:

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

Express will first try the static files in the public / html folder, then in the rest (including public / html), I prefer to put the html files in the root of the public folder or, possibly, in another folder (for example, public-html, static HTML)

+7
source share

All Articles