How to connect knex.js to PostgresSQL database? - postgresql

Hi i'am trying to connect a database to server.js with Knex.js i have tried to add user as postgresql and i tried also to add host as localhost but that didn't work an i always get
Below is when i list all the databases!
Failed to load resource: the server responded with a status of 400 (Bad Request)
Below is a snapshot of my error when i tries to register me!
Below is my register.js that should help with the reigistering to the database!
const handleRegister = (req, res, db, bcrypt) => {
const { email, name, password } = req.body;
if (!email || !name || !password) {
return res.status(400).json('incorrect form submission');
}
const hash = bcrypt.hashSync(password);
db.transaction(trx => {
trx.insert({
hash: hash,
email: email
})
.into('login')
.returning('email')
.then(loginEmail => {
return trx('users')
.returning('*')
.insert({
email: loginEmail[0],
name: name,
joined: new Date()
})
.then(user => {
res.json(user[0]);
})
})
.then(trx.commit)
.catch(trx.rollback)
})
.catch(err => res.status(400).json('unable to register'))
}
module.exports = {
handleRegister: handleRegister
};
Here is my server.js file below!
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');
const register = require('./controllers/register');
const signin = require('./controllers/signin');
const profile = require('./controllers/profile');
const image = require('./controllers/image');
const db = knex({
client: 'pg',
connection: {
host : 'localhost',
user : 'postgres',
database : 'smartbrain1'
}
});
const app = express();
app.use(cors())
app.use(bodyParser.json());
app.get('/', (req, res)=> { res.send(db.users) })
app.post('/signin', signin.handleSignin(db, bcrypt))
app.post('/register', (req, res) => { register.handleRegister(req, res, db, bcrypt) })
app.get('/profile/:id', (req, res) => { profile.handleProfileGet(req, res, db)})
app.put('/image', (req, res) => { image.handleImage(req, res, db)})
app.post('/imageurl', (req, res) => { image.handleApiCall(req, res)})
app.listen(3000, ()=> {
console.log('app is running on port 3000');
})
And here is my databases that i have created in postgreSQL in the terminal as a snapshot!

You should start by just trying to write standalone node app, that connects pg and runs a query. Then You can start integrating with other parts of your app when you know that connecting DB works as expected. Now the question has way too much irrelevant information.
First try to connect your SQL server from shell without using UNIX socket, but with TCP:
psql postgres://postgres#localhost/smartbrain1
If that fails, it probably means that your database is configured so that it does not allow any external TCP connections.
To allow access from localhost to postgres this should do it in pg_hba.conf by setting
host all all 127.0.0.1/32 trust
Also you may need to add password for your postgres user and try connecting with password enabled:
psql postgres://postgres:<password>#localhost/smartbrain1
When connecting from command line works you can try something like this in knex config:
const db = knex({
client: 'pg',
connection: 'postgres://postgres:<password>#localhost/smartbrain1'
});
Some more info for debugging this is found here Knex:Error Pool2 - error: password authentication failed for user and probably in tens of other generic postgres database connection problem questions.

Related

Connecting to Heroku Postgres from Auth0 results in: err no pg_hba.conf entry for host, no encryption

I'm trying to connect to my PostgreSQL database hosted on Heroku through Auth0's Database Connections.
I am getting an error when I try to invoke the Get User script within Auth0's database actions:
no pg_hba.conf entry for host "xx.xxx.xx.x", user "xxx", database "xxx", no encryption
The script looks like this:
function loginByEmail(email, callback) {
const postgres = require('pg');
const conString = configuration.DATABASE_URL;
postgres.connect(conString, function (err, client, done) {
if (err) return callback(err);
const query = 'SELECT id, nickname, email FROM organizations WHERE email = $1';
client.query(query, [email], function (err, result) {
done(); // Close the connection to the database
if (err || result.rows.length === 0) return callback(err);
const user = result.rows[0];
return callback(null, {
user_id: user.id,
nickname: user.nickname,
email: user.email
});
});
});
}
Connection String:
configuration.DATABASE_URL: 'postgres://xxx:xxx#xxx?sslmode=require'
I appended sslmode=require to the end of my connection string to ensure I have a SSL connection to my database.
I have also tried changing sslmode=require to ssl=true, which results in a different error:
self signed certificate
I am unsure where to go from here, so any help would be appreciated.
You should first establish the client and specify the rejectUnauthorized flag, like so:
const client = new postgres.Client({
connectionString: conString,
ssl: { sslmode: 'require', rejectUnauthorized: false }
});
Then, instead of using your postgres to connect, use the client:
client.connect();
client.query(...);
This should solve your problem, and the connection will be encrypted. You won't, however, be protected against Man-In-The-Middle (MITM) attacks, as specified in documentation.
#Pexers solution worked for me, however, somehow it shows TypeScript error. The way I did it is just ssl: true:
const client = new postgres.Client({
connectionString: conString,
ssl: true
});

Mongo DB Connection - Password contains unescaped characters

I am trying to connect to MongoDB but I am getting the "Password contains unescaped characters" error. I have included the useNewUrlParser:true option but I still get the error
See my code below:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config();
connectDB().catch(err => console.log(err));
async function connectDB() {
await mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
})
.then(() => console.log("DB Connection Success"))
.catch((err) => console.log(err));
}
app.listen(8800, () => {
console.log("Backend Server is running");
});
Same problem here... solved with encodeURIComponent on the part of the string that had the password
const uri = "mongodb+srv://username:" + encodeURIComponent("pass#") + "#cluster.yijnb.mongodb.net/db?retryWrites=true&w=majority";
Maybe provide username and password as option:
const options = {
user: <username>,
pass: <password>,
authSource: "admin",
useNewUrlParser: true
};
mongoose.connect(process.env.MONGO_URL, options);
I solved it by changing the password as I tried using several fixes to help me connect with the initial password that contained ".".

Cannot connect to MongoDB - Authentication Failed

Having an issue connecting to MongoDB when starting a new MERN stack project:
server.js code:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
.env file:
ATLAS_URI = mongodb+srv://exampleUser:exampleUserPassword#cluster0.y9bpc.mongodb.net/example-
database?retryWrites=true&w=majority
receiving error:
(node:23036) UnhandledPromiseRejectionWarning: MongoError: Authentication failed.
Not sure what I'm doing wrong here, was just following a tutorial. Only difference from the tutorial is the connection string which also requires a dbname which I created and added. I'm hoping it's something more simple than that. I appreciate any help.
So it appears that I chose to add my own IP address instead of allowing access from anywhere and that was the issue. Hooray!

Can't connect to Mongo Atlas anyway

I am trying to connect to mongoDB atlas.But can't do it anyway.I have tried all options that found on the stackoverflow
My server.js is like as below
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
/*
-------------- Mongo db connection -----------
*/
const mongoose = require('mongoose')
mongoose.connect('mongodb+srv://tintindenmark#gmail.com:*********#cluster0-f9upb.mongodb.net/test?retryWrites=true&w=majority', { useNewUrlParser: true });
mongoose.connection
.once('open', () => console.log('Good to go!'))
.on('error', (error) => {
console.warn('Warning', error);
});
/*
------------------------ Mongo db connection ends ------------------------
*/
app.prepare().then(() => {
const server = express()
server.get('/about', (req, res) => {
return app.render(req, res, '/about', req.query)
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
but i cant do it anyway.I have whitelisted IP addresses from atlast clusters.
Also tried without mongodb+srv.It didnt worked also
Always i am getting this errorMongoNetworkError: failed to connect to server [cluster0-shard-00-01-f9upb.mongodb.net:27017] on first connect [MongoError: Authentication failed.]
I also tried mongodb+srv://tintindenmark#gmail.com:musassmc42#cluster0-f9upb.mongodb.net:27017/test but it also didn't work
So what else i can do to connect??
My mongoose version is : 5.6.6
tintindenmark#gmail.com:musassmc42, this username:password is of your atlas account and not your database.
Created a new user and password for you. Try:
mongodb+srv://testuser:testpassword#cluster0-f9upb.mongodb.net:27017/test
And change all passwords.

Mongo DB connects successful but does not create database

const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
// Connect to mongoose
mongoose.connect('mongodb://localhost:27017/sample')
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
app.get('/', (req, res) => {
const title = 'Welcome';
res.send('ok');
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
I have written this code to connect MongoDB and there is no issue with the connection but when I show my DBS using "> show dbs", I can't see the sample database which I have created. My system is windows 32 bit.
Just connecting to the database won't create it. You need to add something to the database like saving a new document or adding an index.