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}`);
})
Removing
client.end()worked for me. You can then useclient.queryin your routes to run queries.For example,
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
Then, all you need to do is require the client variable wherever your routes are and you can use client.query again.