2

I am trying to implement a simple postgresql / Node.JS site however, I am coming across a TypeError with regards to the res object in the query.js file, when performing the query in postgreSQL to insert into a webpage.

I have created a route/users.js file which renders the site and specifies the 'user' variable as such:

const express = require('express');
const router = express.Router();
const request = require('request');
const db = require('../../config/queries');

router.get('/', (req, res, next) =>
  res.render('users', {
    users: db.getUsers
  })
);

module.exports = router;

Then I have a config/queries.js file which performs the query and returns the result to the above file:

const pool = require('./db');

const getUsers = (req, res) => {
  pool.query('SELECT * FROM users ORDER BY id ASC', (error, results) => {
    if (error) {
      throw error;
    }
    console.log(results.rows);
    res.status(200).json(results.rows);
  });
};

module.exports = {
  getUsers
};

Finally the html site is written as such:

<p> Hello world</p>
<ul> {{users}} 99999 </ul>

When I load the page localhost:5000/users, whilst the console is logging the user data correctly, the following error occurs TypeError: Cannot read property 'status' of undefined and the page displays:

Hello world

99999

It appears the error occurs because the res in res.status(200).json(results.rows) is not defined though I don't know why that would be the case.

Many thanks!

1

1 Answer 1

1

You need to modify your code to get results of the query and then try to render the page. getUsers will not return the results immediately but in a callback. So a correct version maybe like this:

router.get('/', (req, res, next) =>

   getUsers((error,result)=>
   {
      if (error) {
          throw error;
      }
      console.log(results.rows);
      res.render('users', {
        users: results.rows
       })
   })
);

const getUsers = (callback) => {
  pool.query('SELECT * FROM users ORDER BY id ASC',callback )
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! What is the purpose of "const getUsers = (callback)" ? Beginner question but will help my understanding.
@ewldh20 it is defining a function getUsers which takes a callback as parameter. it passes that callback to the postgresql , so that when the results are fetched from database the callback is called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.