1

I am quite new to express and I created a database in Postgres to extract the data about blog posts to place the information in an ejs file. I get the error:

 Cannot read property 'send' of undefined

I've tried to call db.getPosts() with res and req, but it's not possible to set a header again, returns an error.

The problematic chunk of code in my query.js file:

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) or render('blog', {posts: results.rows}) called on res give the exact same error.

Function in server.js that is supposed to use this data is as follows:

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

What do I do wrong? I lack some knowledge, that is for sure, so please, if you can help, explain this briefly to me if possible.

Also, is send() function a correct function to get the data to operate on in server.js? Many tutorials suggest json() but then I don't really get the proper data format, it is just displayed in the browser.

Thank you very much.

Marta P
  • 23
  • 3

2 Answers2

1

Make getPosts receive a callback:

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);
    })
}

Usage would be something like:

app.get("/blog", function (req, res) {
    db.getPosts(function(rows) {
        res.render("blog", {posts: rows})
    });
});
sigmus
  • 2,987
  • 3
  • 23
  • 31
-1

in your getPosts method do not use send. just return results.rows. upate your code like below.

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

also you need to use async await while calling getposts as it is a async function. update the code like below.

app.get("/blog", async function (req, res) {
    const posts = await db.getPosts();
    res.render("blog", { posts: posts });
});
Ahmed Waqas
  • 245
  • 1
  • 3
  • 14