简体   繁体   English

Express.js、CSS 未链接到 Ejs 文件

[英]Express.js, CSS not linking to Ejs file

I believe this is the correct way to link the css to the ejs file, however it's still not working.我相信这是将 css 链接到 ejs 文件的正确方法,但它仍然无法正常工作。 You can see how all my folders are arranged in the pictures provided.您可以在提供的图片中看到我所有的文件夹是如何排列的。 图1 图2 在此处输入图像描述

In your server.js file, use this line instead of the one you have:在你的server.js文件中,使用这一行而不是你拥有的那一行:

app.use(express.static(path.join(__dirname, "/public")));

The line above tells express where to find public assets.上面的行告诉express在哪里可以找到公共资产。 With this, evrytime you write / in a ejs file, you are already in the public folder.有了这个,每次你在ejs文件中写/时,你已经在公共文件夹中。

You will for example link your css file like so (I assume your css styles are inside public/css/styles.css ):例如,您将像这样链接您的 css 文件(我假设您的 css styles 在public/css/styles.css内)

<link href="/css/styles.css" rel="stylesheet">

your problem is not with the link tag in your Ejs file.您的问题不在于 Ejs 文件中的链接标记。 the problem is with defining the path for your file inside the server.js file问题在于在 server.js 文件中定义文件的路径

the solution is to use static method inside the express 'use' middleware as the following:解决方案是在 express 'use' 中间件中使用 static 方法,如下所示:

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

this means that you are telling express where to find and serve static files.这意味着您要告诉 express 在哪里可以找到和提供 static 文件。

for linking the css file, all you have to do inside your Ejs file is to add a link tag as follows:要链接 css 文件,您只需在 Ejs 文件中添加一个链接标签,如下所示:

<link href="/css/styles.css" rel="stylesheet" type="text/css">

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

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