快递提供相对于路线的静态资产文件而不是绝对(Express serving static asset files relative to the route instead of absolute)

编程入门 行业动态 更新时间:2024-10-26 01:26:59
快递提供相对于路线的静态资产文件而不是绝对(Express serving static asset files relative to the route instead of absolute)

在快递中我有以下路线:

app.get('/story/:username', function(req, res){ res.render('dashboard.ejs'); });

在此之前,我提供位于/public任何静态文件:

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

现在我相信这是服务于根目录,所以当我访问路径http://localhost:8080/story/user17它仍然可以从http://localhost:8080/css/main.css提取我的静态文件,如css/main.css http://localhost:8080/css/main.css 。 相反,当我尝试加载页面并检查控制台时,我一直看到这个错误:

GET http://localhost:8080/story/css/main.css (404)

对于我的所有静态文件。 为什么它试图从相对目录而不是绝对根加载我的所有静态文件,我该如何解决它?

In express I have the following route:

app.get('/story/:username', function(req, res){ res.render('dashboard.ejs'); });

And before that I serve any static files located in /public:

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

Now I believed that this was serving the root directory, so that when I visited the path http://localhost:8080/story/user17 it would still be able to pull my static files such as css/main.css from http://localhost:8080/css/main.css. Instead when I tried to load the page and checked the console I kept seeing this error:

GET http://localhost:8080/story/css/main.css (404)

for all of my static files. Why is it attempting to load my all of static files from a relative directory instead of the absolute root, and how can I fix it?

最满意答案

将dashboard.ejs的CSS文件路径从css/main.css更改为../css/main.css以便可以从浏览器看到的页面中找到它/story/someUser

Change the path to your CSS file in dashboard.ejs from css/main.css to ../css/main.css so that it can be found from a page the browser sees as /story/someUser

更多推荐

本文发布于:2023-07-26 05:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1271360.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:相对于   静态   而不是   快递   路线

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!