0

I am trying to write a basic express server code. However, the HTML file that gets served on a particular route does not render the static files (css, js and image files). Can anyone tell me what's wrong with my code? The following code includes the router function. FYI, the code is running on Ubuntu.

I have already used the express.static() function. However, it still does not seem to be working.

var express = require('express');
var router = express.Router();
var app = express();
app.use(express.static(__dirname+'/stat'));
router.get('/',(req,res)=>{
    res.send("Welcome to the home page");
});

router.get('/show',(req,res)=>{
    res.sendFile(__dirname+'/index.html');
})

router.get('*',(req,res)=>{
    res.send("Error 404");
});

module.exports = router;
Azzabi Haythem
  • 2,141
  • 7
  • 25
  • 30
Black Wind
  • 193
  • 8
  • Could you maybe show the HTML file? – julianYaman May 14 '19 at 15:54
  • 1
    Probably the path to the files is just wrong. – Quentin May 14 '19 at 15:54
  • @Quentin This was also my first thought. – julianYaman May 14 '19 at 16:18
  • I did try to include html in my question initially - but stackoverflow isn't showing the code. And the path is right. I checked it twice. Could you share the code if you were to include such a static file? The directory structure is: the_main_folder which contains the server.js,router.js and index.html files and a sub-directory(named 'stat') which contains the style.css and script.js files. – Black Wind May 14 '19 at 18:51
  • BTW @julianYaman since I have two js files (one the actual server.js file and one to handle routing aka router.js) do I include the express.static() statement in both of them? – Black Wind May 14 '19 at 19:07
  • @BlackWind No, you don't have to. You include `express.static()` inside the file, where you load express. – julianYaman May 14 '19 at 20:09

1 Answers1

1

One way to go about this would be to move the JavaScript and CSS files you want to serve to a public folder in the root directory and then access them like this:

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

However, it is usually safer to use the Node.js path module to access the relative path of the folder from which you want to serve these static files. This should do:

const path = require('path')
app.use(express.static(path.join(__dirname, 'stat')));

I think the docs will offer some more help.