【问题标题】:Problem with getting data from database, "render" function error从数据库获取数据的问题,“渲染”功能错误
【发布时间】:2019-05-21 20:02:47
【问题描述】:

我对表达很陌生,我在 Postgres 中创建了一个数据库来提取有关博客文章的数据,以将信息放在一个 ejs 文件中。 我得到了错误:

 Cannot read property 'send' of undefined

我尝试使用resreq 调用db.getPosts(),但无法再次设置标头,返回错误。

我的query.js 文件中有问题的代码块:

const getPosts = (_req, res) => {
    pool.query('SELECT * FROM blog_posts', (error, results) => {
        console.log(error);
        // console.log(results.rows);
        if (error) {
            throw error
        }
        return res.send(results.rows );
    })
}

send(results.rows)render('blog', {posts: results.rows}) 调用 res 给出完全相同的错误。

server.js 中应该使用此数据的函数如下:

app.get("/blog", function (req, res) {
    const posts = db.getPosts();
    res.render("blog", { posts: posts });
});

我做错了什么?我缺乏一些知识,这是肯定的,所以如果你能提供帮助,请尽可能简单地向我解释一下。

另外,send() 函数是否是一个正确的函数来获取要在server.js 中操作的数据?许多教程建议json(),但我并没有真正得到正确的数据格式,它只是显示在浏览器中。

非常感谢。

【问题讨论】:

    标签: node.js postgresql express


    【解决方案1】:

    getPosts 接收回调:

    const getPosts = (callback) => {
        pool.query('SELECT * FROM blog_posts', (error, results) => {
            console.log(error);
            // console.log(results.rows);
            if (error) {
                throw error
            }
            callback(results.rows);
        })
    }
    

    用法类似于:

    app.get("/blog", function (req, res) {
        db.getPosts(function(rows) {
            res.render("blog", {posts: rows})
        });
    });
    

    【讨论】:

      【解决方案2】:

      在您的 getPosts 方法中不要使用发送。只返回results.rows。更新您的代码,如下所示。

      const getPosts = () => {
          pool.query('SELECT * FROM blog_posts', (error, results) => {
              console.log(error);
              // console.log(results.rows);
              if (error) {
                  throw error
              }
              return results.rows;
          })
      }
      

      您还需要在调用 getposts 时使用 async await,因为它是一个异步函数。更新如下代码。

      app.get("/blog", async function (req, res) {
          const posts = await db.getPosts();
          res.render("blog", { posts: posts });
      });
      

      【讨论】:

      • await 在这种情况下不会起作用,因为函数都没有返回承诺,回调也不是异步的
      • posts 在您的路线中将是 undefined
      • 是的,它们是未定义的,你知道为什么吗?
      • @MartaP 与这个问题和答案无关的在这里stackoverflow.com/questions/14220321/…
      猜你喜欢
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 1970-01-01
      相关资源
      最近更新 更多