NodeJS 在for循环中未定义Posts

klh5stk1  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(95)
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}`);
});

个字符
index.js中的index.ejs当我使用for循环来呈现我正在获取的信息时,引用错误帖子没有定义,但我在index.js中定义了数组

hk8txs48

hk8txs481#

正如Sha'an已经评论的那样:
在你的EJS中修改变量名。它是“posts”而不是“Posts”。
JavaScript是区分大小写的。您正在将数组作为postsp)传递,但您正在尝试重写PostsP):

<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>

字符串

相关问题