首页 > 解决方案 > 在 ejs 中集成您的 public/css 文件

问题描述

请帮我检查我的代码是否有任何错误,因为 app.css 文件不起作用。

const express = require("express");
const app = express();
const port = process.env.PORT || 4000

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

app.set('views', './views');
app.set('view engine', 'ejs');

app.get("/posts", function(req, res){
var posts = [
    {title: "Once upon a time", author: "Richard"},
    {title: "The Way", author: "Ikoro"},
    {title: "I Love Critics", author: "Emmanuel"},
    {title: "Adorable Bunny", author: "Christian"}
]
res.render("posts", {posts: posts});
});

这是我的公共目录,其中包含 app.css 文件

body {
background: #ffff00;
color: #800080;
}

标签: node.jsexpressejs

解决方案


请 westdabestdb 查看视图/模板代码

<link rel="stylesheet" href="../public/app.css">
<h1>The Post Page</h1>

<!-- for Loop Syntax for Embedded JavaScript Templates -->
<% for(var i = 0; i < posts.length; i++){ %>
<li>
    <%= posts[i].title %> - <strong><%= posts[i].author %></strong>
</li>
<% } %>

<!-- forEach Loop Syntax for Embedded JavaScript Templates -->
<% posts.forEach(function(post){ %>
<li>
    <%= post.title %> - <strong><%= post.author %></strong>
</li>
<% }) %>

推荐阅读