Express.js - 图像仅在一个页面上呈现 [英] Express.js - Image only renders on one page

查看:90
本文介绍了Express.js - 图像仅在一个页面上呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Pug和Express将图像显示在多个页面上。
但是我遇到了一些麻烦。



图像应该在路径'/','data','update 。它已成功呈现在根目录'/'上,但之后从Sources文件夹中消失。



在app.js中,我有关于所有路由处理程序的中间件:

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

在公共文件夹中,我还有文件styles.css,它可以在其他页面上呈现。 / p>

我通过放入

  img(src =/ image .jpg)

而不是

  img(src =image.jpg)

有人知道为什么那是什么?

解决方案

让我们想象一下您的网页上有以下网址(加载图片或其他内容):

 < img src =image.jpg/> 

现在,如果该模板位于主页面上,例如 http://example.com/ ,它将指向 http://example.com/image.jpg 这将会使用快速静态路由,一切正常。现在您访问 http://示例.com / something ,并且相对于我们而言,它会指向 http://example.com/something/image.jpg 。该文件不存在。现在,如果您将图片更改为:

 < img src =/ image.jpg/> 

它将相对于 root http://example.com ),因此它将始终有效。


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?

解决方案

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.

这篇关于Express.js - 图像仅在一个页面上呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆