在Express JS中将HTML转换为哈巴狗时出现错误

时间:2018-09-19 06:55:30

标签: node.js express pug

我是node.js的新手。我收到此错误

  

TypeError:/home/agile/projects/nodekb/views/index.pug:6       
4 | h1#{title}       
5 | ul     
> 6 |每篇文章,我在文章中       
7 | li = article.title

     

无法读取未定义的属性“ length”       在评估时(在包装时评估(/home/agile/projects/nodekb/node_modules/pug-runtime/wrap.js:6:10),   :28:32)       在评估时(在包装时评估(/home/agile/projects/nodekb/node_modules/pug-runtime/wrap.js:6:10),   :47:4)       在模板上(在包装时评估(/home/agile/projects/nodekb/node_modules/pug-runtime/wrap.js:6:10),   :58:136)       在Object.exports.renderFile(/home/agile/projects/nodekb/node_modules/pug/lib/index.js:427:38)       在Object.exports.renderFile(/home/agile/projects/nodekb/node_modules/pug/lib/index.js:417:21)       在View.exports .__ express [作为引擎](/home/agile/projects/nodekb/node_modules/pug/lib/index.js:464:11)       在View.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)       在Function.render(/home/agile/projects/nodekb/node_modules/express/lib/application.js:592:3)       在ServerResponse.render(/home/agile/projects/nodekb/node_modules/express/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...');
});

views / layout.pug

doctype html
html
    head
        title Knowledgebase
    body   
        block content
        br
        hr
        footer
            p Copyright © 2018

1 个答案:

答案 0 :(得分:1)

您的问题是您忘记在articles方法中包含res.render数据。

要解决您的问题,只需更改此代码:

res.render('index',{
    title:'Articles'
});

对此:

res.render('index',{
    title:'Articles',
    articles // Equivalent to `articles: articles`
});

这会将articles变量数据提供给模板引擎。