简体   繁体   English

如何修复 Express + ESJ 项目中的 CSS 样式表路径

[英]How can I fix CSS stylesheet path in Express + ESJ project

I have used Express and EJS for my project.我在我的项目中使用了Express 和 EJS I would like that when I enter " localhost:PORT/posts/:articleName ", a.ejs file to be rendered.我希望当我输入“ localhost:PORT/posts/:articleName ”时,要呈现 a.ejs 文件。 The only problem is that even if I have app.use(express.static(__dirname + "/public"));唯一的问题是,即使我有app.use(express.static(__dirname + "/public")); it doesn't work like it should.它不像它应该的那样工作。 When I am inspecting the stylesheet link in the post.ejs file, it is " localhost:PORT/posts/style.css ".当我检查post.ejs文件中的样式表链接时,它是“ localhost:PORT/posts/style.css ”。 But I want the path to be " localhost:PORT/style.css " in order to work.但我希望路径为“ localhost:PORT/style.css ”才能工作。 How can I fix the path?如何修复路径?

Project structure: https://imgur.com/a/UrYY9lK项目结构: https://imgur.com/a/UrYY9lK

Code for GET request for / GET 请求的代码 /

app.get("/posts/:articleName", (req, res) => {
for(obj of posts) {
    if(lodash.lowerCase(obj.title) === lodash.lowerCase(req.params.articleName)) {
        console.log("it s a match");
        res.render("post.ejs", {title: obj.title, 
            content: obj.content});
        return;
    }
}
res.redirect("/")
});

posts = array of JSON objects帖子= JSON 对象数组

post.ejs = the file containing only specific article, it doesn't work as it should, because it doesn't load the style.css file from public directory. post.ejs = 仅包含特定文章的文件,它不能正常工作,因为它不会从公共目录加载 style.css 文件。

Try this variant, because you wrote this part of code incorrect:试试这个变种,因为你写的这部分代码不正确:

 app.use(express.static('public'));

Apparently, you need to have a "/" before your css file or put it in another subdirectory to get the correct path显然,您需要在 css 文件之前有一个“/”或将其放在另一个子目录中以获得正确的路径

so link rel="stylesheet href="/style.css" does work, but link rel="stylesheet href="style.css" doesn't.所以link rel="stylesheet href="/style.css"确实有效,但link rel="stylesheet href="style.css"无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM