0
嘗試我的手在一點節點,但我無法讓我的EJS模板呈現一些非常基本的數據。我有兩個控制器 - 一個用於基本的家庭/ about/contact和另一個用於職位。當我到/帖子,正確的頁面呈現,但沒有數據和出現一個錯誤,說「帖子沒有定義。」我不明白爲什麼會出現這種情況。乾杯。EJS變量定義問題
var express = require('express');
var router = express.Router();
var posts = [{
id: 0,
title: "This is an example post.",
author: "Tony",
content: "This is some content for a post"
}];
router.get('/', function(req, res) {
res.render("posts/index");
});
router.get('/new', function(req, res) {
res.send("NEW");
});
router.get('/:id', function(req, res) {
res.send("SHOW");
});
router.post('/', function(req, res) {
res.send("CREATE");
});
router.get('/:id/edit', function(req, res) {
res.send("EDIT");
});
router.put('/:id', function(req, res) {
res.send("UPDATE");
});
router.delete('/:id', function(req, res) {
res.send("DELETE");
});
module.exports = router;
和HTML:
<!DOCTYPE html>
<html>
<head>
<title>Posts</title>
</head>
<body>
<h1>hello</h1>
<nav>
<ul>
<li><a href="/posts">Posts</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
<%= posts %>
<% for(var i=0; i < posts.length; i++) { %>
<%= posts[i].id %>
<h2><%= posts[i].title %></h2>
<h4><%= posts[i].author %></h4>
<p><%= posts[i].content %></p>
<% } %>
<button><a href="/posts/new">New</a></button>
</body>
</html>
和app.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var port = process.env.PORT || 3000;
var router = require("./config/routes");
var posts = require("./config/posts");
// Set the view directory to /views
app.set("views", __dirname + "/views");
// Let's use the Express templating language
app.set("view engine", "ejs");
// Setup public folder to serve static files
app.use(express.static(__dirname + "/public"));
// Setup app to parse req.body
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/', router);
app.use('/posts', posts);
app.listen(port);