尝试加载页面时出现此错误
SyntaxError: Unexpected identifier in C:\Users\Vuyisile\Desktop\Vuyi projects\programming\back end practice\myapp\views\posts.ejs while compiling ejs
Google说这是一个错字错误,但我检查了所有内容,一切正常,没有错字,但它只是拒绝加载页面。我正在尝试将我的部分内容加载到我的帖子页面中。这就是我的app.js文件的样子
var express = require("express");
var app = express();
app.use(express.static("public"));
app.get("/", function(req, res){
res.render("home.ejs");
});
app.get("/posts", function(req,res){
var posts = [
{Title: "The wicked witch of the west", Author: "Rowan Atiknson"},
{Title: "Stone henge", Author: "Wouldrow Wilson"},
{Title: "Why the treaty of Versailles flopped", Author: "Kudzaishe Sitshebo"},
];
res.render("posts.ejs", {posts: posts});
});
app.listen(3000, function(){
console.log("The server has been started!");
});
这是我的posts.ejs文件的外观
<% include partials/header.ejs %>
<h1>Book authors and titles</h1>
<% for(var i = 0; i < posts.length; i++){ %>
<li>
<%= posts[i].Title %> - <strong><%= posts[i].Author %></strong>
</li>
<% } %>
<% include partials/footer.ejs %>
我的项目文件结构看起来像这样
|_myapp.js
|_views_
|posts.ejs
|home.ejs
|_partials_
|_header.ejs
|_footer.ejs
在您的代码中,还为我们的Express应用程序添加view engine。
var express = require("express");
var app = express();
app.use(express.static("public"));
app.set('view engine', 'ejs');
app.get("/", function(req, res){
res.render("home.ejs");
});
app.get("/posts", function(req,res){
var posts = [
{Title: "The wicked witch of the west", Author: "Rowan Atiknson"},
{Title: "Stone henge", Author: "Wouldrow Wilson"},
{Title: "Why the treaty of Versailles flopped", Author: "Kudzaishe Sitshebo"},
];
res.render("posts.ejs", {posts: posts});
});
app.listen(3000, function(){
console.log("The server has been started!");
});
注意我们如何使用res.render()向用户发送视图。重要的是要注意,res.render()将在视图的视图文件夹中查找。因此,我们只需要定义页面/索引,因为完整路径是视图/页面/索引。