Search code examples
node.jsherokupsqlknex.js

Unable to connect to heroku psql database using knex.js


I am unable to connect to psql database on heroku through backend in express.js .What can be the reason? Plz someone answer!

server.js code is:

const { handleRegister } = require('./Controllers/Register');
const knex = require('knex');
const db = knex({
    client: 'pg',
    connection: {
      connectionString : process.env.DATABASE_URL,
      ssl: true
    }
 });
app.post('/register', (req,res) => {
    handleRegister(req,res,db,bcrypt);  
})

And the code inside register.js is:

const saltRounds = 10;
const handleRegister = (req,res,db,bcrypt) => {
    const {firstname, lastname, email, password} = req.body;
    if(!email || !firstname || !lastname || !password){
        return res.status(400).json("Incorrect from submission!");
    }
    bcrypt.genSalt(saltRounds, function(err, salt) {
        bcrypt.hash(password, salt, null , function(err, hash) {
            db.transaction(trx => {
                trx.insert({
                    hash: hash,
                    email: email
                })
                .into("login")
                .returning("email")
                .then(mail => {
                    return trx("users")
                    .returning('*')
                    .insert({
                        email: mail[0],
                        firstname: firstname,
                        lastname: lastname,
                        name: firstname + " " + lastname,
                        joined: new Date()
                    })
                    .then(user => {
                        res.json(user[0]);
                    }).catch(err => {res.json("Unable to Register!")});
                })
                .then(trx.commit)
                .catch(trx.rollback)
            })
            .catch(err => {
                res.json("Error while Registring user!");
            })  
        }); 
    });
}

I'm getting response "Error while Registring user!",But I successfully connected to the database using cmd, here is ss:

Screenshot of Database connected successfully

Can someone tell me how to fix this issue???


Solution

  • It may be the fact that you are using free version of Heroku. Setting ssl to
    ssl: { rejectUnauthorized: false } worked for me when I had similar problem. However, this is not safe for production use! Use it only in the case of personal project.