TimK
TimK

Reputation: 135

node-postgres why is req.query.record empty?

When I start my nodejs app (with dust) on localhost:3000 the following code is used to grab all rows from my products tables (postgres db) and display them on my index page. It seemed to work fine last week.

app.get('/', async (req, res) => {
    var parms = req.query.record;    
    const results = await pool.query('SELECT * FROM products WHERE id = $1',[parms], function (err, result) {
        if (err) {
            return console.error('error running query', err);
        }
        res.render('index', { products: result.rows });        
    });
});

For some reason now "req.query.record" is empty "[ ]" so no results are displayed on my index page.

If I navigate to localhost:3000/?record=3 it works fine and I can see the one record on my index page.

Also, if I edit the "results" in the original code and change [parms] to [3] then it works fine as well and displays that one record on my index page.

what would cause var parms = req.query.record; to return an empty object? Is that the expected behavior?

Upvotes: 1

Views: 481

Answers (1)

TimK
TimK

Reputation: 135

Okay, I think I have it. Bergi (it is the request) is correct and it was the expected behavior. I started the code from a tutorial posted before July 2017. the original pg.connect was hard deprecated. pg.connect not a function?

As a result I started hacking together something with the new pg.Pool(...).connect(...). The method described in my original question must have gotten mushed up with something else. As far as I know there is no need to process any query string from the index page when I am trying to return all rows from a table.

There is nothing after http://localhost:3000 which is why the result was an empty object. that is the expected behavior. http://localhost:3000/?record=3 did return the one row because req.query.record picked out [3] from the query string which is the expected behavior. The method in the original question would be used for returning one row from the table when the id is passed in the query string.

for my purposes, returning all rows, I replaced my app.get with...

app.get('/', async (req, res) => {    
    await pool.query('SELECT * FROM library', function (err, result) {
        if (err) {
            return console.error('error running query', err);
        }                
        res.render('index', { recipes: result.rows });
    });
});

If I wanted to use both methods I guess I would first run a check to see if there is a query string then proceed with the original app.get if true. else run the second app.get method to get all rows.

I just started with NodeJS and Postgres but am not sure why I didn't notice that from the get-go. Not sure if this will be a useful question/answer for anyone but I'll leave it up.

Upvotes: 1

Related Questions