[英]Express.js, CSS not linking to Ejs file
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.