Question

I have 2 different directories inside one directory. The first is views which contains all swig views such as newpost.html. The other is temp_images which contains butterfly.png.

Within newpost.html I have,

<div id="image">{{post.image}}</div> <!-- this prints `butterfly.png`-->
<img src="../temp_images/{{post.image}}"></img> <!-- shows broken img link-->

Swig prints the text, but it will not show the butterfly. I have no idea why and I double checked the HTML. I also tried

<img src="../temp_images/butterfly.png"></img>

And that didn't work either. Could there be a problem with how I'm using Swig? I'm also using Node, Express, Mongo.

Was it helpful?

Solution

If you are using express, then you should probably have your /temp_images directory inside of public or whatever you have set up to serve static files. For example, in your app.js, you should have a line like this somewhere:

app.use(express.static(path.join(__dirname, 'public'), { maxAge: 60*60*1000 }));

You can find more information about .static on the ConnectJS site, since Express gets this from Connect. Connect.static doc. maxAge provides a caching directive to the browser, in this case that the file is good for an hour.

Your views directory is typically only being accessed via your template engine and wouldn't (shouldn't) be directly exposed for static downloads.

Also note that your URL for the image is interpreted relative to the URL being displayed at the browser, not relative to the file be rendered on the server (though they could be perfectly parallel structures). I just mention it - you could look at the network section of your browser's developer tools to see the exact GET request it is making for the image.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top