Express.js - Image only renders on one page

若如初见. 提交于 2019-12-02 17:54:23

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/49705304/express-js-image-only-renders-on-one-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!