提问人:Naved Khan 提问时间:11/15/2023 更新时间:11/15/2023 访问量:36
帖子未在 for 循环中定义
Posts is not defined in for loop
问:
const express = require("express");
const app = express();
const path = require("path");
let port = 8080;
app.use(express.urlencoded({extended: true}));
app.set("views engine","ejs");
app.set("views",path.join(__dirname,"views"));
app.use(express.static(path.join(__dirname,"public")));
let posts =[
{username : "Naved",content : "I love coding"},{username : "Noman",content : "I love studying"}{username : "Saimoon",content : "I love cooking"},] ;
app.get("/posts",(req,res)=>{
res.render("index.ejs", {posts});
});
app.listen(port,()=>{
console.log(`app is listening at the port ${port}`);
});
<body>
<h1>Quora Posts</h1>
<% for(post of Posts) { %>
<div class="post">
<h3 class="user">@ <%= post.username %></h3>
<h4 class="content"><%= post.content %></h4>
</div>
<% } %>
</body>
index.ejs 中的 index.ejs 当我使用 for 循环呈现我得到的信息时,引用错误帖子未定义,但我在 index.js 中定义了数组
答:
1赞
eekinci
11/15/2023
#1
正如沙安已经评论的那样:
更正 EJS 中的变量名称。它是“帖子”而不是“帖子”。
JavaScript 区分大小写。您正在将数组作为 (p) 传递,但您正在尝试遍历 (P):posts
Posts
<body>
<h1>Quora Posts</h1>
<% for(post of posts) { %>
<div class="post">
<h3 class="user">@ <%= post.username %></h3>
<h4 class="content"><%= post.content %></h4>
</div>
<% } %>
</body>
评论