flexayoung
flexayoung

Reputation: 1

Express.js - Image only renders on one page

I'm trying to make an image appear on multiple pages using Pug and Express. But I've been running into some trouble.

The image should be rendered on the page on the routes '/', 'data', 'update'. It is successfully rendered on the root '/', but afterwards, disappears from the Sources folder.

In app.js I have this middleware about all my route-handlers:

app.use(express.static(path.join(__dirname, '/public')));

In the public folder I also have the file styles.css which renders fine on the other pages.

I fixed it by putting

  img(src="/image.jpg") 

instead of

   img(src="image.jpg)

Anybody know why that is?

Upvotes: 0

Views: 435

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138537

Lets imagine you got the following url on your page (that loads an image or whatever):

  <img src="image.jpg" />

Now if that template is on the main page, e.g. http://example.com/, it will point to http://example.com/image.jpg which will hit the express static route and everything is fine. Now you visit http://example.com/something, and as tze image url us relative, it will point to http://example.com/something/image.jpg. And that file does not exist. Now if you change the image to:

  <img src="/image.jpg" />

It will be relative to the pages root (http://example.com) and therefore it will always work.

Upvotes: 1

Related Questions