Why is my express code not rendering css and javascipt files?

29
May 15, 2019, at 11:10 PM

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;
Answer 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.

READ ALSO
Keycloak Policy Enforcing for nodejs REST Api

Keycloak Policy Enforcing for nodejs REST Api

It's the first time asking something here, so excuse if I forget to provide some information or any other mistakesSorry for the text wall

48
Sum of n number inside array is x number and create subset of result

Sum of n number inside array is x number and create subset of result

For example, if you have an array [20, 6, 7, 8, 50] and if I pass value 21 it should return [6,7,8] this sub arrayNote: the sum of number should be in sequence

13