我是node.js的新手 . 我收到了这个错误
TypeError:/home/agile/projects/nodekb/views/index.pug:6 4 | h1# 5 | ul> 6 |每篇文章,我在文章7 | li = article.title无法读取eval中未定义的属性“length”(包装时的eval(/home/agile/projects/nodekb/node_modules/pug-runtime/wrap.js:6:10),:28:32)at eval(eval at wrap(/home/agile/projects/nodekb/node_modules/pug-runtime/wrap.js:6:10),:47:4)at template(eval at wrap(/ home / agile / projects / nodekb) /node_modules/pug-runtime/wrap.js:6:10),:58:136)at Object.exports.renderFile(/home/agile/projects/nodekb/node_modules/pug/lib/index.js:427:38 )在View.exports .__ express [作为引擎]的Object.exports.renderFile(/home/agile/projects/nodekb/node_modules/pug/lib/index.js:417:21)中(/ home / agile / projects / nodekb) /node_modules/pug/lib/index.js:464:11)在try.render(/home/agile/projects/nodekb/node_modules/express/lib/view.js:135:8)的tryRender(/ home / agile) /projects/nodekb/node_modules/express/lib/application.js:640:10)在ServerResponse的Function.render(/home/agile/projects/nodekb/node_modules/express/lib/application.js:592:3) . 渲染(/ home / agile / projects / nodekb / node_modules / expre SS / LIB / response.js:1008:7)
这是我的代码,views / index.pug
extends layout
block content
h1 #{title}
ul
each article, i in articles
li= article.title
app.js
const express = require('express');
const path = require('path');
//init app
const app = express();
//load view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine','pug');
//home route
app.get('/', function(req,res){
let articles =[
{
id:1,
title: 'Article 1',
author: 'Bhakti Thakkar',
body: 'This is article one'
},
{
id:2,
title: 'Article 2',
author: 'Jeel Thakkar',
body: 'This is article two'
},
{
id:1,
title: 'Article 3',
author: 'Sonal Thakkar',
body: 'This is article three'
}
];
res.render('index',{
title:'Articles'
});
});
//add route
app.get("/articles/add",function(req,res){
res.render('add_article',{
title:'Add Articles'
})
});
//start server
app.listen(3000, function(){
console.log('Server started on port 3000...');
});
意见/ layout.pug
doctype html
html
head
title Knowledgebase
body
block content
br
hr
footer
p Copyright © 2018
1 回答
您的问题是您忘记在
res.render
方法中包含articles
数据 .要解决您的问题,只需更改此代码:
对于这一个:
这将为模板引擎提供
articles
变量数据 .