1

I generated project structure using express-generator In app.js I have following code :

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var minifyHTML = require('express-minify-html');
var minify = require('express-minify');



var indexRouter = require('./routes/index');
var aboutRouter = require('./routes/about');
var productsRouter = require('./routes/products');
var contactRouter = require('./routes/contact');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');


// Minifying HTML Code
app.use(minifyHTML({
    override:      true,
    exception_url: false,
    htmlMinifier: {
        removeComments:            true,
        collapseWhitespace:        true,
        collapseBooleanAttributes: true,
        removeAttributeQuotes:     true,
        removeEmptyAttributes:     true,
        minifyJS:                  true
    }
}));

//Minifying JS Code
app.use(minify({
  cache: false,
  uglifyJsModule: null,
  errorHandler: null,
  jsMatch: /js/,
  cssMatch: /css/,
  jsonMatch: /json/,
  sassMatch: /scss/,
  lessMatch: /less/,
  stylusMatch: /stylus/,
  coffeeScriptMatch: /coffeescript/,
}));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/about-us', aboutRouter);
app.use('/products', productsRouter);
app.use('/contact-us', contactRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

In productsRouter I have following code :

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/hospital-cubical-track-system', function(req, res, next) {
  res.render('products/hospital-cubical-track-system', { title : 'Hospital Cubical Track System'});
});

router.get('/telescopic-iv-bag-hanger', function(req, res, next) {
  res.render('products/telescopic-iv-bag-hanger', { title : 'Telescopic IV Bag Hanger'});
});

router.get('/wall-protection-system', function(req, res, next) {
  res.render('products/wall-protection-system', { title : 'Wall Protection System'});
});

router.get('/hospital-blinds', function(req, res, next) {
  res.render('products/hospital-blinds', { title : 'Hospital Blinds'});
});

router.get('/nurse-call-system', function(req, res, next) {
  res.render('products/nurse-call-system', { title : 'Nurse Call System'});
});

router.get('/hospital-linen', function(req, res, next) {
  res.render('products/hospital-linen', { title : 'Hospital Linen'});
});


module.exports = router;

Now on sub routes like "products/hospital-cubical-track-system", Static css files of design are not loading while on "/, /about, /contact" loading css js static files fine. kindly help me

  • You can try `app.use(express.static(path.join(__dirname, '../public')));` – Pardeep Dhingra Sep 20 '18 at 09:50
  • Thank you pradeep to reply, but your method will not work. `../public` would create problem in root routers like /about – Piyush Gupta Sep 20 '18 at 09:53
  • Using absolute path over relative path should solve this problem. `app.use(express.static(__dirname + '/public'));` Ref: http://expressjs.com/en/api.html – Pardeep Dhingra Sep 20 '18 at 09:56
  • you are right, but it is not serving static files on child routes of a route – Piyush Gupta Sep 20 '18 at 10:02
  • Can you please give an example of a static file's path that is not loading? – Joseph Sep 20 '18 at 10:35
  • Thanks joseps for replying. CSS, JS, imaages files path not loading. When I look at source code, chiled routs actually loading localhost/products/css/style.css instead of localhost/css/style.css. This is happening only child of product router. but working fine with other main routers – Piyush Gupta Sep 20 '18 at 11:31
  • How do you reference the static files in your HBS templates? It sounds like you might be using some relative paths which only resolve correctly when you're "zero or one level deep", e.g., in "/", "/about", or "/contact". – Petr Broz Sep 20 '18 at 12:28
  • in hbs layout file, i am using path like 'css/style.css', 'js/main.js' – Piyush Gupta Sep 20 '18 at 12:32
  • 1
    Are you using relative references for the asset files? That seems like what's wrong. So instead of using `` you should use `` (notice the beginning `/` indicating to use the root of your website. See [this](https://stackoverflow.com/a/24028813/1148564) for more info. – Joseph Sep 20 '18 at 17:01
  • Thanks joseph serido. You helped me a lot and gave solution fast. It worked – Piyush Gupta Sep 21 '18 at 09:48
  • @PiyushGupta you're welcome. I added an answer so others can benefit as well. Feel free to accept it if it solved your problem. – Joseph Sep 21 '18 at 11:18
  • Thank you @joseph serido. I have posted another question, could you please analyse that ? I want to use localhost smtp with nodemailer – Piyush Gupta Sep 21 '18 at 12:38

1 Answers1

6

From the comments it sounds like you are you using relative references for the asset files in your html pages when you should use absolute references.

So instead of using:

<link rel="stylesheet" type="text/css" href="css/style.css" />

You should use:

<link rel="stylesheet" type="text/css" href="/css/style.css" />

Notice the beginning / indicating to use the root of your website. See this link for more info.

Joseph
  • 5,070
  • 1
  • 25
  • 26