Node-postgres: Error: getaddrinfo ENOTFOUND undefined undefined:5432

Created on 19 Jul 2016  Â·  9Comments  Â·  Source: brianc/node-postgres

var express       = require('express');
var pg            = require('pg');
var CONSTANT      = require('../src/constant.js');
var router = express.Router();
var connectionString = CONSTANT.DB_NAME+'://'+CONSTANT.DB_USERNAME+':'+CONSTANT.DB_PASSWORD+'@'+CONSTANT.DB_URL+':'+CONSTANT.DB_PORT+'/'+CONSTANT.DB_SCHEMA;
var client = new pg.Client(connectionString);
client.connect();

var config = {
  user: CONSTANT.DB_USERNAME,
  database: CONSTANT.DB_SCHEMA,
  host: CONSTANT.DB_HOST,
  password: process.env.PGPASSWORD,
  port: CONSTANT.DB_PORT
};

console.log("config : "+JSON.stringify(config));
var pool = new pg.Pool(config);

pool.on('error', function(error, client) {
  if(err) {
    console.log(err);
  }
})

router.get('/testing', function(req, res, next) {
  console.log("--------------");
})

module.exports = router;

Below is the error am getting

events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: getaddrinfo ENOTFOUND undefined undefined:5432
    at errnoException (dns.js:27:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:78:26)

Also this link https://github.com/brianc/node-postgres doesn't seem to be passing the host/hostname to the config param
NodeJS version is 4.4.2... PostgreSQL version is 9.5.2

Looking at the error message undefined:5432 it looks like it is not finding the DB host name.

Most helpful comment

Hi @brianc... I deleted my node_modules and did npm install again.
After that am not getting that error. Assuming its resolved?

Just wanted to confirm with you before I close this thread.

All 9 comments

don't pass a connectionString to the client, pass the same var config as you're passing to the pool. You might want to log out the config before you pass it to the client too. My gut is telling me the variables in your config or your CONSTANT construct are undefined

Please ignore line 5,6&7. I have commented them.
Below is my constant file contents

exports.DB_NAME                         = "postgres";
exports.DB_USERNAME                = "abcd";
exports.DB_PASSWORD                = "abcd1234";
exports.DB_HOST                         = "abcd.cvg87ikjlfjt.us-east-1.rds.amazonaws.com";
exports.DB_PORT                         = "5432";
exports.DB_SCHEMA                       = "ABCD";

And when I print the config object console.log("config : "+JSON.stringify(config)); I see the desired output in the log.

Am assuming the property key host is the culprit. Or one of the key.
This is my guess based on the error messge Error: getaddrinfo ENOTFOUND **undefined undefined:5432**

try this

var express       = require('express');
var pg            = require('pg');
var CONSTANT      = require('../src/constant.js');
var router = express.Router();
var config = {
  user: CONSTANT.DB_USERNAME,
  database: CONSTANT.DB_SCHEMA,
  host: CONSTANT.DB_HOST,
  password: process.env.PGPASSWORD,
  port: CONSTANT.DB_PORT
};

console.log("config : "+JSON.stringify(config));
var pool = new pg.Pool(config);
pool.query('SELECT NOW()', function(err, res) {
  if (err) throw err
  console.log(res.rows)
})

router.get('/testing', function(req, res, next) {
  console.log("--------------");
})

module.exports = router;

That should work if you're using pg>=6.0.0

I have PostgreSQL 9.5.2
When I saw your above code, I was sure that I would have the same error and I did get the same error message.
Reason being, the error is thrown when we are passing the config object to pg.Pool.
So I still get the same error message.

events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: getaddrinfo ENOTFOUND undefined undefined:5432
    at errnoException (dns.js:27:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:78:26)
[nodemon] app crashed - waiting for file changes before starting...

I'm pretty sure this is related to something in your environment and not node-postgres itself. I suggest you edit the pg module source code under node_modules/pg/lib/connection.js and log out the actual parameters passed to the socket being created in there in your environment. From there, trace back where the connection parameters are turning into undefined - I'm 100% sure pg connects to postgres no problemo for me, travis, etc...so...you'll have to do some digging on this one your own. Please come back & let me know what you find out though!

Hi @brianc ... Just a quick update. When I run the test.js as a standalone Node app... It runs fine without any issues.
I have structured my REST service project using express-generator which creates a project structure for me.
Below is the package.json

{
  "name": "Test",
  "version": "0.0.1",
  "private": true,
  "author": "Test",
  "license": "Test",
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.15.1",
    "debug": "~2.2.0",
    "express": "~4.13.4",
    "jade": "~1.11.0",
    "morgan": "~1.7.0",
    "serve-favicon": "~2.3.0",
    "cookie-parser": "~1.4.3",
    "pg": "~6.0.1",
    "q": "~1.4.1",
    "request": "~2.73.0",
    "https": "~1.0.0",
    "path": "~0.12.7",
    "ssl-root-cas": "~1.2.1"
  },
  "devdependencies": {
    "nodemon": "~1.9.2",
    "node-inspector": "~0.12.8"
  }
}

So when I naviagate to that project and say nodemon or npm start the ./bin/www script gets executed. Below is the www script file

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('Test:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

Below is my app.js file

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var regions = require('./routes/regions');
var postal = require('./routes/postal');
var test = require('./routes/test');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/api/', routes);
app.use('/api/regions', regions);
app.use('/api/postal', postal);
//app.use('/api/test', test);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

./routes/test is the file that I have posted initially.
Sorry for the long post but just trying to make sure that I give as much information as possible.

Also when I say var pool = new pg.Pool(config); can you please let me know how the flow happens internally?

Hi @brianc... I deleted my node_modules and did npm install again.
After that am not getting that error. Assuming its resolved?

Just wanted to confirm with you before I close this thread.

Glad you got it figured out!! :dancer:

On Fri, Jul 22, 2016 at 9:52 AM, arjungowdaa [email protected]
wrote:

Hi @brianc https://github.com/brianc... I deleted my node_modules and
did npm install again.
After that am not getting that error. Assuming its resolved?

Just wanted to confirm with you before I close this thread.

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/brianc/node-postgres/issues/1086#issuecomment-234565365,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AADDodMNBBuITCFR66SsmCs2spkrx4aXks5qYNkfgaJpZM4JQJ0-
.

if you are writing react native, using expo . clear app data and cache. restart app

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ClueLessEggHead picture ClueLessEggHead  Â·  3Comments

chrisjensen picture chrisjensen  Â·  4Comments

dipakdas99 picture dipakdas99  Â·  3Comments

AhmedBHameed picture AhmedBHameed  Â·  3Comments

spollack picture spollack  Â·  4Comments