connect ElephantSQL with node.js

2.8k views Asked by At

I am new to programming I tried to Use ElephantSql postgres database server in node..but its not connecting..(i used the same code from doumentation.)

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const PORT = process.env.PORT || 3001;

const app = express();

app.use(cors())
app.use(bodyParser.json());


var pg = require('pg');
var client = new pg.Client("postgres:/.elephantsql.com:The Actual url");

client.connect(function(err) {
  if(err) {
    return console.error('could not connect to postgres', err);
  }
  client.query('SELECT NOW() AS "theTime"', function(err, result) {
    if(err) {
      return console.error('error running query', err);
    }
    console.log(result.rows[0].theTime);
    // >> output: 2018-08-23T14:02:57.117Z
    client.end();
  });

});

app.get('/', (req, res) => { res.send('its working') })

app.listen(PORT, () => {
  console.log(`app is running on PORT:${PORT}`);
})
1

There are 1 answers

0
john94 On

Removing client.end() worked for me. You can then use client.query in your routes to run queries.

For example,

app.get('/', async (req, res) => {
    try {
        const results = await client.query('SELECT * FROM your_table');
        res.json(results);
    } catch (err) {
        console.log(err);
    }
}

I would however suggest putting the block of code that you copied in a separate file as the documentation says. Then export client.

For example, we'll call the file elephantsql.js

var pg = require('pg');
var client = new pg.Client("postgres:/.elephantsql.com:The Actual url");

client.connect(function(err) {
  if(err) {
    return console.error('could not connect to postgres', err);
  }
  client.query('SELECT NOW() AS "theTime"', function(err, result) {
    if(err) {
      return console.error('error running query', err);
    }
    console.log(result.rows[0].theTime);
    // >> output: 2018-08-23T14:02:57.117Z
  });

});

module.exports = client;

Then, all you need to do is require the client variable wherever your routes are and you can use client.query again.

const client = require('./elephantsql');

app.get('/', async (req, res) => {
    try {
        const results = await client.query('SELECT * FROM your_table');
        res.json(results);
    } catch (err) {
        console.log(err);
    }
}