表示静态投放错误的路径 [英] Express static serving wrong path

查看:43
本文介绍了表示静态投放错误的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搞砸了express.js并构建了一些基本功能,但是如果URL的根目录比一个目录的目录长,那么从错误的位置进行静态静态服务就存在问题.请参阅下面的示例.

I am messing around with express.js and have built some basic functionality but am having issues with express static serving from the wrong place if the URL is longer than one directory from root. See the examples below.

我正在使用记录在案的常规方法来使用static.

I am using the normal documented approach to using static.

app.use(express.static(__dirname + '/public'));

并设置了两条路线.例如.

And have set up a couple of routes. eg.

app.get('/signup', function(req, res) {
    res.render('signup.ejs');
});

在链的末尾带有404钩扣.

With a 404 catch at the end of the chain.

app.get('*', function(req, res){
    res.status(404).render('404');
});

如果我点击了诸如localhost:3000localhost:3000/login之类的页面,这些页面已定义为路由,那么一切都很好.即使我遇到未定义的localhost:3000/foo路线,也可以正确呈现所有存在的图像的404.

If I hit page such as localhost:3000 or localhost:3000/login which are defined routes, all is well. Even if I hit an undefined route of localhost:3000/foo, I get the 404 rendered correctly with all images present.

但是,如果我再进一步做类似localhost:3000/login/foo之类的操作,则所有图像均丢失,并且在浏览器控制台中出现以下地址时会出现错误.

However if I go one further and do something like localhost:3000/login/foo all the images are missing and I will get an error in the browsers console with the following address.

http://localhost:3000/login/img/site-brand.png

在定义了多个目录的路由上也是如此.

This happens the same on routes defined with more than one directory too.

我解释了快递网站上的文档,无论调用静态图像是什么,它将从root的公共目录(包含js,img和css目录)中提供.

I interpreted the docs on the express website that regardless of what was calling for the static image it would be served from the public directory in root, which contains a js, img, and css directories.

我的问题是,我误解了什么?以及如何表达始终与根相对的服务?

My questions are, what have I misinterpreted? and how do I get express to always serve relative to root?

推荐答案

我写了整个问题,然后意识到,当我在.ejs文件中设置src=""标记时,我使用的是相对路径,而不是绝对路径.我没有删除问题,而是决定回答该问题并将其发布给其他人.

I wrote the whole question then realised that when I had set up the src="" tags in my .ejs files I had used relative paths, not absolute. Rather than delete the question I decided to answer it and post it for others.

因此,不应使用src="img/my-image.png",而应使用src="/img/my-image.png".前斜杠表示请求是相对于root的,而不是发出请求的路径.

So instead of using src="img/my-image.png" it should be src="/img/my-image.png" The leading slash indicates that the request is relative to root not the path that is making the request.

那里的基本Web开发内容.我本来应该第一次看到它,但是已经很晚了,我挤满了新框架,这反过来又从我的小脑筋中挤出了一些琐碎的东西.

Basic web development stuff there. I should have seen it first time out but its late, and I am cramming my head full of new frameworks which is in turn squeezing the more trivial stuff out of my small brain.

这篇关于表示静态投放错误的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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