Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving static files on a url with parameters in Express

I am using the handlebars template engine with Express. When hitting endpoints without parameters, all my static files are served up. This is not the case when a parameter is included.

app.engine('.hbs', hbs(handlebarsOptions));
app.set('view engine', '.hbs');

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

Here is the endpoint I am trying to use.

app.get('/projects/:name', function(req, res) {
  if(req.params.name === 'batteryapp') {
    res.render('project', {name: 'BatteryApp'});
  }
});

I have seen an example that apparently works if you use res.sendFile(). However, res.render() must be used when using a template engine.

like image 287
Reagan Cuthbertson Avatar asked Feb 04 '23 10:02

Reagan Cuthbertson


1 Answers

It sounds like you're not using absolute URL's (starting with a /) for the static resources in your template, so they are being requested relative to /projects/batteryapp instead of the root.

So instead of something like this:

<script src="js/app.js"></script>

Use this:

<script src="/js/app.js"></script>
like image 100
robertklep Avatar answered Feb 08 '23 11:02

robertklep