redirect image file get requests express 4.x and handlebars

328 Views Asked by At

I have the following routes:

index.js:

router.get('/', function(req, res, next) {
  var flag = "true";
  var hflag = "true";  
  res.render('index',{title:"My Blog",header: hflag, login: flag, categories:blogEngine.getBlogEntries()});
});

router.get('/article/:id', function(req, res) {
    var entry = blogEngine.getBlogEntry(req.params.id);
    var img = entry.img;
    res.render('article',{title:entry.title, gedjit:entry});
    res.redirect(img);
});

In the '/' route, I load a list of images from the public static file folder 'images'. This works fine until I click on one of the images. I want to show the clicked image in a new page.

Here is my handlebars file;

article.hbs:

<h1>{{gedjit.title}}</h1>
<div class="gedjit">
  <img class="img" src="{{gedjit.img}}">
</div>
<br>
<p>Description: {{gedjit.description}}</p>

The problem is that handlebars is sending a "localhost/article/images/source.jpeg" route instead of a route to "localhost/images/source.jpeg" like in the / route.

Is there a way to redirect the route and remove article from the get request sent from handlebars to the server?

1

There are 1 best solutions below

0
On

I found out what the problem was.

Firstly I my image source url did not have / in front of it; "images/sources.jpeg" instead of "/images/sources.jpeg"

Secondly I used two routes to send the partial and the image file separately so that I do not get a can't set headers after they are sent error from express.

The /articles/:id route now looks like this;

index.js

router.get('/article/:id', function(req, res) {
    var entry = blogEngine.getBlogEntry(req.params.id);
    var img = entry.img;
    res.render('article',{title:entry.title, gedjit:entry});
    res.sendFile(img);
});