javascript - 帕格 - 无法读取未定义的属性

标签 javascript node.js

我想通过 getList 函数显示数据库中的所有帖子:

在我的服务层中,我有以下功能:

function getList() {
        const res = knex('posts').where({
            deleted: false,
        }).orderBy('createdAt')
        console.log("getList: " + res)
        return res
    }

在路由文件中,我调用我的 getList 函数:

var express = require('express');
var router = express.Router();
const service = require('../services/post')

/* GET home page. */
router.get('/', function (req, res, next) {
  postList = service.getList().then(data => console.log(JSON.stringify(data)))
  console.log("Postlist: " + postList)

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

module.exports = router;

最后我想在我的 index.pug 文件中显示结果:

  table.table
    thead.thead-inverse
      tr
        th #
        th Title
        th Description  
        th Created At
        th Action
    tbody
      //TODO: If post is empty
      for post in postList
        tr
          td(scope='row')=post.id
          td=post.title
          td=post.description
          td=post.createdAt
          td
            a.btn.btn-primary(href='/edit', role='button') Edit 

但是,我收到以下错误:

C:\Users\user\Desktop\Coding Projects\learning_crud\views\index.pug:22 20| for post in postList 21| tr > 22| td(scope='row')=post.id 23| td=post.title 24| td=post.description 25| td=post.createdAt Cannot read property 'id' of undefined

TypeError: C:\Users\user\Desktop\Coding Projects\learning_crud\views\index.pug:22
    20|       for post in postList
    21|         tr
  > 22|           td(scope='row')=post.id
    23|           td=post.title
    24|           td=post.description
    25|           td=post.createdAt
Cannot read property 'id' of undefined
    at eval (eval at wrap (C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:152:61)
    at eval (eval at wrap (C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:173:4)
    at template (eval at wrap (C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:225:119)
    at Object.exports.renderFile (C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\pug\lib\index.js:428:38)
    at Object.exports.renderFile (C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\pug\lib\index.js:418:21)
    at View.exports.__express [as engine] (C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\pug\lib\index.js:465:11)
    at View.render (C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\express\lib\view.js:127:8)
    at tryRender (C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\express\lib\application.js:640:10)
    at Function.render (C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\express\lib\response.js:971:7)
    at C:\Users\user\Desktop\Coding Projects\learning_crud\routes\index.js:10:7
    at Layer.handle [as handle_request] (C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\user\Desktop\Coding Projects\learning_crud\node_modules\express\lib\router\index.js:281:22

此外,我得到以下控制台输出:

Listening on localhost:8080
getList: select * from "posts" where "deleted" = false order by "createdAt" asc
Postlist: [object Promise]
GET / 500 326.920 ms - 4255
[{"id":6,"title":"Excepturi rerum ratione omnis aut quo.","description":"Eum nostrum vel reiciendis qui. Nam sapiente unde deserunt totam at dolores. Tempor
e corrupti fugiat et consequuntur vero. Laboriosam autem mollitia odit cum repellat.","deleted":false,"createdAt":"2017-09-17T01:15:31.865Z","updatedAt":"20
17-09-16T22:02:41.233Z","deletedAt":"2017-09-17T00:02:15.235Z"}]
GET /css/bootstrap/bootstrap.min.css 304 3.464 ms - -
GET /css/style.css 304 0.913 ms - -
GET /js/bootstrap/bootstrap.min.js 304 1.173 ms - -

我的 pug 文件有问题吗?有什么建议我做错了什么吗?

感谢您的回复!

更新

我将路由器更改为以下内容并且它可以工作:

router.get('/', function (req, res, next) {
  knex('posts').select().where({
    deleted: false,
  }).orderBy('createdAt').then(query => {
    res.render('index', {
      postList: query
    }); 
  })
});

有什么建议吗?

最佳答案

在 pug js 中,您使用 each 执行循环。所以你必须做类似的事情:

each post in postList

了解更多关于Pug each的信息

或者您可以使用 for 循环,例如:

- for (post in postList) {
    // pug code in between
- }

引用:https://pugjs.org/language/code.html#unbuffered-code

更新

您之前的代码有一个问题,您正在发出异步请求,因此您需要在从函数 getList 返回的 promise 的 then 内部编写代码。因此需要将代码更改为:

service.getList().then(data => {
    console.log(JSON.stringify(data))
    res.render('index', {
        postList: data
    });
})

关于javascript - 帕格 - 无法读取未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46263741/

相关文章:

javascript - 每次提交时,Rails 4 Ajax 在同一页面上多次渲染部分

javascript - 正则表达式:仅允许使用数字或包含 '-' 和 '_' 的字母数字,但不允许包含包含 '-' 和 '-' 的数字

node.js - 如何开始使用 OpenSeadragon?

node.js - socket.io 的可扩展架构

javascript - 使用 Jquery 在菜单周围添加 div

javascript - 还有其他方法可以获取 map 的 map 吗?

javascript - 根据屏幕尺寸更改功能

javascript - 无法在 Node.js 中检索 Redis 中的值?

javascript - 我如何解决集中听众的个人 promise ?

node.js - Mongoose 种群 - 回调与执行