首页 > 解决方案 > Cannot read property 'query' of null?

问题描述

var express = require('express');
var pg = require('pg');
var app = express();

var connectionString = "postgres://...";

app.get('/', function (req, res, next) {
    pg.connect(connectionString, function (err, client, done) {
        if (err) {
            console.log("not able to get connection " + err);
            res.status(400).send(err);
        }
        client.query('SELECT * FROM employee WHERE empid=$1', [1], function (err, result) {
                done(); // closing the connection;
                if (err) {
                    console.log(err);
                    res.status(400).send(err);

                }
                res.status(200).send(result.rows);

            });
    });
});

app.listen(3000, function () {
    console.log('Server is running.. on Port 3000');
});

This is my nodejs file and the connectionString is database information that connected heroku and postgreSQL.

But when I run this one, I only get

client.query('SELECT * FROM employee WHERE empid=$1', [1], function (err, result) {
               ^

TypeError: Cannot read property 'query' of null

How can I solve it?

标签: node.jspostgresqlheroku

解决方案


In your error handler here:

    if (err) {
        console.log("not able to get connection " + err);
        res.status(400).send(err);
    }
    client.query(...)

You need to add a return so that after you send the error status, the code does not continue to try to execute client.query() because client does not have a valid value in it if there was an error. So, change to this:

    if (err) {
        console.log("not able to get connection " + err);
        res.status(400).send(err);
        return;
    }
    client.query(...)

Though it has less of a consequence, the same is true here:

            if (err) {
                console.log(err);
                res.status(400).send(err);

            }
            res.status(200).send(result.rows);

Where you need to add a return:

            if (err) {
                console.log(err);
                res.status(400).send(err);
                return;
            }
            res.status(200).send(result.rows);

The overall issue in these two cases is that while res.status(...).send(...) sends the response back to the client, it does not stop your code from continuing to execute after that so you still need proper flow control with if/else or an appropriate return to control the flow of execution of the code so after an error it doesn't immediately go execute other parts of the code that you don't want it to.


推荐阅读