Can't establish SSL connection to MongoDB from NodeJS program - node.js

I am trying to connect a mongod instance from NodeJS program using Mongoose that configured with SSL connection but I'm getting the following error on the mongod console: "Error receiving request from client: SSLHandshakeFailed: The server is configured to only allow SSL connections."
The mongod instance is initiated as follow:
mongod --sslMode requireSSL --sslPEMKeyFile C:/Users/MyUsername/Path/mongodb.pem
I tried to use MongoClient instead of mongoose but nothing new happened.
This is my piece of code:
if(envConfig.config.db.tls === true){
let certFile = [fs.readFileSync("C:/PATH/TO/Key/mongoDB.pem")];
mongoose.connect("mongodb://localhost:27017/DB_NAME?ssl=true",{
server:{
sslValidate: true,
sslCA: certFile
}
});
}else{
mongoose.connect(`mongodb://${dbUrl}`,options);
}
It is not something about the PEM file because when I start the mongod as I wrote and use SSL connection with MongoDB Compass using the same PEM file from the code - it works.
MongoDB version: 3.6.0
Mongoose version: 4.13.6
Happy if someone will guide me what am I doing wrong.

I think you should refer to the question Mongoose SSL, connection not accepted
You should specify {server: {ssl: true} parameter and I think your problem will be solved

If you initiate MongoDB daemon with private key and certificate
mongod --sslMode requireSSL --sslPEMKeyFile C:/Users/MyUsername/Path/mongodb.pem --sslCAFile C:/Users/MyUsername/Path/mongodb.crt
You can connect from Node JS like
if(envConfig.config.db.tls === true){
let key = fs.readFileSync("C:/Users/MyUsername/Path/mongodb.pem");
let crt = fs.readFileSync("C:/Users/MyUsername/Path/mongodb.crt");
mongoose.connect("mongodb://localhost:27017/DB_NAME?ssl=true",{
server:{
"sslValidate" :true
"sslKey": key,
"sslCert": crt, // if you have one certificate you can use `sslCert` parameter
}
});
}else{
mongoose.connect(`mongodb://${dbUrl}`,options);
}
More detail explanation of SSL connection via Node JS you can go here

Solved!
Problem was using express-session middelware and trying to connect the DB with incorrect connection string, that what caused the problem.

Related

Unable to connect to remote redis host [nodeJS]

const redis = require('redis');
require('dotenv').config();
console.log(process.env.redisHost, ':', process.env.redisPort);
const redisClient = redis.createClient({
host: process.env.redisHost,
port: process.env.redisPort,
password: process.env.redisKey
});
redisClient.connect();
redisClient.on('error', err => console.log('Redis error: ', err.message));
redisClient.on('connect', () => console.log('Connected to redis server'));
module.exports = redisClient;
I tried this sample from redis docs but still I'm getting an error stating:
Redis error: connect ECONNREFUSED 127.0.0.1:6379
I logged the environment host and port variables to the console and I got the remote host ipv4 address, but still the client is trying to connect to localhost instead of remote host (I purposely uninstalled redis from my local device to check if the client is working as it is supposed to). I also confirmed that the remote redis host is working perfectly.
I also tried different methods like :
https://cloud.google.com/community/tutorials/nodejs-redis-on-appengine
redis.createClient(port, host, {auth_pass: password});
But still, I got the same error.
I am able to connect to the redis host via commandline:
redis-cli.exe -h XX.XX.XX.XXX -a Password
XX.XX.XX.XXX:6379> set name dhruv
OK
XX.XX.XX.XXX:6379> get name
"dhruv"
XX.XX.XX.XXX:6379> exit
I'm trying to use redis on nodejs for the first time, so don't have a proper idea but I think I am doing everything right.
Any solution/workaround will be helpful :D
It worked with this code:
const url = `redis://${process.env.redisHost}:${process.env.redisPort}`;
const redisClient = redis.createClient({
url,
password: process.env.redisKey
});
redisClient.connect();
can you check if in the destination the port is reachable. it maybe the firewall block your access

Server runs locally but crashes on Heroku

I deployed my server on Heroku but when I make any requests it returns a "500 Internal Server" error. It runs fine locally though. Could anyone help figure out what's going on?
When I check my logs this is what I'm getting.
2021-06-08T18:43:09.715406+00:00 app[web.1]: error: no pg_hba.conf entry for host "3.90.138.215", user "detmvsbueicsez", database "da9nlve42hcp91", SSL off
Repo Link: https://github.com/zcason/Restaurant-Review-Server
Live App: https://restaurant-review-phi.vercel.app/
As mentioned here on Heroku help, this indicate that there was a failed authentication attempt to the database, so the connection couldn't be established. This can happen because of different reasons.
In your case i suspect it's something related to not using ssl.
So after taking a look on the code provided in the github repo i noticed you are using knex and getting the connection string from .env
Try this :
Just add this ?ssl=true and append it to the end of DATABASE_URL in your .env file.
Edit your server.js (i didn't take a good look at the code so you need to add this ssl: { rejectUnauthorized: false } in your connection config) :
const db = knex({
client: 'pg',
connection: {
connectionString: DATABASE_URL,
ssl: { rejectUnauthorized: false }
}
});
Also make sure you're using the wright user and password and database name etc
OR Alternatively :
Run this command heroku config:set PGSSLMODE=no-verify in terminal to omit the ssl configuration object and set PGSSLMODE to no-verify

Connecting to a self signed mongodb server though nodejs driver doesn't require `pem` key

I am using nodejs mongodb driver to connect to a self signed mongodb instance. The MongoDB version is 4.0.0. And the nodejs driver version is 3.1.1. Below is the command to launch a self signed mongodb instance:
mongod --port 27018 --sslMode requireSSL --sslPEMKeyFile mongodb.pem --dbpath data
when I connect to this server with nodejs, I can use below options without specifying pem file:
const options = {
ssl: true,
};
MongoClient.connect('mongodb://localhost:27018', options, (err, driver) => {
if(err) {
console.error(err);
return null;
}
});
I wonder why the connection option doesn't require pem file. Why does it work just with a ssl option.

Connection to MongoDb failed

I was trying to connect my mongodb with node server using command prompt.
I started mongodb my mongod --dbpath E:\node start\node\data
Then I installed mongodb dependencies using npm install mongodb
I added some code into my app.js which is described below :
app.js
var mongodb = require('mongodb'); //acquiring mongodb native drivers
var mongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:7000/myDatabase'; //connection url
mongoClient.connect(url, function(err,db){
if(err){
console.log('Unable to connect to mongodb server. Error :' , err);
}
else{
console.log('Connection established to', url);
db.close();
}
});
when I ran app.js in command prompt, following error occured :
Unable to connect to mongodb server. Error :{[ MongoError : connect ECONNREFUSED] name : 'MongoError' , message: 'connect ECONNREFUSED' }
I cannot understand what the problem is and what should I do next.
MongoDB usually runs on port 27017, but you're trying to connect to port 7000. Try changing your url variable.
var url = 'mongodb://localhost:27017/myDatabase';
You know mongoDB has their default port no 27017.
And You have written 7000.
So Try to Change port no to 27017.
ok !!!!!!!
The error says you do not have mongodb running. You should check if your mongodb is running or not. If its running then you should check on what port it is running on.
The default port for mongodb is 27017. If you have not configured your mongodb to run on port 7000 then changing var url = 'mongodb://localhost:7000/myDatabase'; to var url = 'mongodb://localhost:27017/myDatabase'; will work for you.

Redis in Nodejs on Cloud9 IDE: [Error: Auth error: undefined]

Here is my code:
var express = require("express"),
app = express(),
server = require("http").createServer(app),
io = require("socket.io").listen(server),
redis = require("redis"),
env = {PORT: process.env.PORT || 8080, IP: process.env.IP || "localhost"};
client = redis.createClient(env.PORT , env.IP);
client.on("error", function(err) {
console.log(err);
});
server.listen(env.PORT);
console.log("Server started # " + env.IP + ":" + env.PORT);
After trying to run, I received the followings on the console:
Running Node Process
Your code is running at 'http://modified.address.c9.io'.
Important: use 'process.env.PORT' as the port and 'process.env.IP' as the host in your scripts!
info: socket.io started
Server started # modified.ip.address.1:8080
[Error: Auth error: undefined]
I tried establishing the connection, and it connects to the IP and PORT perfectly. However, the error [Error: Auth error: undefined] appears and stops there. I Googled the error, the supports from the IDE I used..., and surprisingly, there are only 7 links to my problems. So I think it may be a hole in my knowledge or it is not really a problem yet a thing I don't know to work it out. All I could pull out from those Google results were (I was not sure) I need to use client.auth(pass) right after creating it. But where should I find the password? When I installed it npm install redis I didn't configure anything and wasn't told to set password whatsoever. So I reach the impasse.
I use Cloud9 IDE (c9.io), and the modules used as shown in the code above.
----With best regards,
----Tim.
I've found out what was wrong.
I did install Redis, but that is a Redis library that acts like a bridge between Redis driver and NodeJS. On Cloud9, I have to manually install Redis, too.
So it would take 2 commands to actually install Redis:
Install the Redis Driver on Cloud9
nada-nix install redis
Install Redis library for NodeJS
npm install redis
Thanks for anyone who was trying to help me.
You can run the redis-server using your own config file.You can create your own config like below.
//port and ip of ur redis server
port 6371
bind 127.0.0.1
//password for this server
requirepass ucanmentionurpwd
//storing snapshots of the data
save 60 1
dbfilename dump.rdb
dir /tmp/db
//starting redis server
redis-server //ur config file location
See this link for redis configuration
https://raw.github.com/antirez/redis/2.6/redis.conf
If you mention requirepass with your password means only you need to do
client.auth('urPwd');
Otherwise no need to call the client.auth method.

Resources