How do I connect my app to Redis Labs server? - node.js

I've been trying to connect my node app to my remote Redis Labs server. I have the endpoint which from what I can discover, is my host and port (host.com:port). I've been trying to connect to the cloud server by using
const redis = require('redis');
const client = redis
.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST)
.on('error', err => console.error('FUCK', err));
client.on('connect', function(err, res) {
console.log('redis is connected!');
});
but I continue to get an error. "Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379"
I'm sure this is a simple fix, but I just don't understand how to get it to work. Any help would be much appreciated!

Figured it out. I knew it was a simple fix. Just had to call client.auth(process.env.REDIS_PASSWORD)
const client = redis.createClient(
process.env.REDIS_PORT,
process.env.REDIS_HOST
);
client.auth(process.env.REDIS_PASSWORD);

Related

Connecting to redis using tls (ssl) and auth_token password in nodeJS

I am trying to connect to a redis instance in aws. I can connect to it using something like
redis-cli -h localhost -p 6379 -a <auth_token> --tls PING
However when I try this using node (redis library v4.2.0) doing something like this, it hangs
const redis = require("redis");
(async () => {
const client = redis.createClient( {
auth_pass:
"<auth_token>",
tls: { servername: "localhost", port: 6379 },
});
client.on("error", (err) => {
console.log("Redis Client Error", err);
});
client.connect();
console.log(await client.ping());
})();
Portforwarding is setup for redis in aws, which is why localhost is used.
The auth token is the same token I entered to the sparkleformation when redis was configured. both resting and transit encryption has been configured as well.
I have been trying to poke around on google for an answer, however there seem to be a lot of old documentation out there and none of the new ones are clear as to how to get a connection working using tls and an auth token. Any idea how to get this working?
If anybody is running into the same issue, I was able to get it working using ioredis instead.
const Redis = require("ioredis");
(async () => {
const redisRef = new Redis("rediss://:<auth_token>#localhost:6379");
console.log(await redisRef.ping());
})();
and setting this environment variable when running locally:
export NODE_TLS_REJECT_UNAUTHORIZED=0

Redis Connection Error with Heroku Redis Instance: Redis connection to failed - read ECONNRESET heroku instance

I have a node js app. And I use Redis from Heroku Redis(with async-redis library).
Actually, I have two different Heroku accounts and two different Node.js apps hosted by Heroku. But except Redis credentials, both apps are the same code.
The interesting thing on my app I can connect to first Heroku Redis instance. But I can't connect to new Heroku Redis instance. Besides I deleted and created new instances, bu they don't work.
The error is:
Error: Redis connection to redis-123.compute.amazonaws.com:28680 failed - read ECONNRESET\n
at TCP.onStreamRead (internal/stream_base_commons.js:162:27)
My connection statement like this:
var redisPassword = 'password123';
var redisOptions = { host: 'redis-123.cloud.redislabs.com', port: '17371', auth_pass: redisPassword }
//var redisPassword = 'password123';
//var redisOptions = { host: 'redis-123.compute.amazonaws.com', port: '28680', auth_pass: redisPassword }
const client = redis.createClient(redisOptions);
client.on('connect', function () {
console.log('Redis client connected');
});
client.on('error', function (err) {
console.log('An error on Redis connection: ' + err);
});
As I can see there is the only thing that different on Heroku Redis instances. My first Redis instance hosts at cloud.redislabs.com but the second instance(that i can't connect) hosts at compute.amazonaws.com.
Any help will be much appreciated.
I encountered this situation and it turned out the with "Heroku Redis" connecting via TLS worked (the url that starts with rediss) once I adjusted my client code to connect following the example provided in the Heroku redis docs:
https://devcenter.heroku.com/articles/connecting-heroku-redis#ioredis-module
const Redis = require("ioredis");
const client = new Redis(process.env.REDIS_URL, {
tls: {
rejectUnauthorized: false
}
});
Where process.env.REDIS_URL is rediss://<details>
I couldn't find the root problem. But after comment of Chris, I checked again Heroku Redis addons I used.
Heroku Redis gives me an instance from amazonaws.com, and Redis Enterprise Cloud gives me an instance from redislabs.com. When I added and used Redis Enterprise Cloud, I could connect to it.
But Heroku Redis's connection problem still is a secret for me.

Not able to connect to heroku redis

const redis = require("redis");
let client = redis.createClient({
host: process.env.host,
port: process.env.port,
password:process.env.password
});
(async () => {
client.on('error', (err) => console.log('Redis Client Error', err));
await client.connect();
console.log("connected to redis")
})();
I have added redis-heroku addon to my project, Now I am trying to access it from my code but its giving me this error: "AuthError: ERR Client sent AUTH, but no password is set".
Also when I am trying to connect from terminal, I am able to connect to it but when I type any redis command , I get this "Error: Connection reset by peer".
If I am using this on my localsystem and local redis server its working fine
it will be helpful if anyone can provide me a working code of heroku redis, I think redis has two urls: REDIS_URL, REDIS_TLS_URL. The problem might be arising because of this tls(more secure)
Kinldy help me
Thanks
Heroku redis does not expose a host, port, and password variables. Instead they expose a REDIS_URL that contains all of those things in one string.
I believe you need to call createClient like this...
createClient({
url: process.env.REDIS_URL
});
In node-redis v4 the host and port should be inside a socket object, not directly on the main config object (see https://github.com/redis/node-redis/blob/master/docs/client-configuration.md):
const client = redis.createClient({
socket: {
host: process.env.host,
port: process.env.port
},
password: process.env.password
});

How to make 2 nodejs servers connect with SSL websocket?

I am trying to make 2 servers communicate via socket.io library and SSL.
This used to work until an upgrade of socket.io package (can't tell you which).
I have managed to fix secure connection with a browser. I have also made it work between unsecure (http) servers. But the secure (https) servers refuse to connect between themselves. You may argue that socket.io is not made for server to server communications, but it would save me lots of work to fix it.
I am now running:
node: 7.5.0
express: 4.16.2
socket.io (and socket.io-client): 2.0.3
I cannot even make simple examples below work (removing all my middleware).
node server
// Use SSL certificate
const cert_path = "..";
const fs = require('fs');
const https_options = {
key: fs.readFileSync(cert_path+'/privkey.pem'),
cert: fs.readFileSync(cert_path+'/cert.pem')
};
const app = require('express')();
const https = require('https');
const server = https.createServer(https_options, app);
const io = require('socket.io')(server);
server.listen(8000);
io.on('connection', function (socket) {
console.log("connected");
});
node client
const io = require('socket.io-client');
const socket = io.connect(
'https://localhost:8000',
{secure: true}
);
socket.on("connect", function () {
console.log("connected");
});
Nothing happens, none of them connect. Any idea why?
EDIT: I'm getting both connect_error and reconnect_error that pop every 5s on client side:
{ Error: xhr poll error
at XHR.Transport.onError (../node_modules/engine.io-client/lib/transport.js:64:13)
at Request.<anonymous> (../node_modules/engine.io-client/lib/transports/polling-xhr.js:128:10)
at Request.Emitter.emit (../node_modules/component-emitter/index.js:133:20)
at Request.onError (../node_modules/engine.io-client/lib/transports/polling-xhr.js:310:8)
at Timeout._onTimeout (../node_modules/engine.io-client/lib/transports/polling-xhr.js:257:18)
at ontimeout (timers.js:365:14)
at tryOnTimeout (timers.js:237:5)
at Timer.listOnTimeout (timers.js:207:5) type: 'TransportError', description: 503 }
Digging further in the errors, I see it may come from the certificate. But while I apply several workarounds of SO, I'm getting consecutively ECONNREFUSED, UNABLE_TO_VERIFY_LEAF_SIGNATURE, and finally DEPTH_ZERO_SELF_SIGNED_CERT...
After trying hard:
re-generate my Let's Encrypt certificate
re-generate my self-signed certificates (openssl) and use them by server+client
tinker with socket.io connect options (secure, rejectUnauthorized, ..)
tinker with nodejs global setup even (process.env['NODE_TLS_REJECT_UNAUTHORIZED'])
I finally stumbled on this page of github. It solved my issue and it's worth sharing it.
node client
const https = require('https');
https.globalAgent.options.rejectUnauthorized = false;
const io = require('socket.io-client');
const sockets = io.connect('https://localhost:8001', {agent: https.globalAgent});
Even if I would have preferred getting my connection authorized in the first place, this will work for me.

MongoError: failed to connect to server [localhost:27017] on first connect (ECONNREFUSED)

I just added MongoDB to the dependencies of my Node.js project created with the npm init command. My index.js code is:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/mydatabase';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
db.close();
});
But when I execute the code it throws the following error:
AssertionError: null == { MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
I really don't know how to fix it. I followed some guides that reported the same error but I couldn't fix it.
Should I poen a port on my modem? Should I replace "localhost" with my IP? Should I do anything else?
Please help me!
UPDATE:
I installed a MongoDB server on my Android device and replacing the url variable with mongodb://ANDROID-DEVICE-LOCAL-IP:27017/mydatabase it now works.
How can I accomplish it placing the database on my computer? Is the firewall blocking incoming connections? Is this why it works on Android but not on Windows?
I fixed the issue!
I ran mongod -dbpath "MY-PATH" in the cmd and now it works.
The error occurred because nothing was listening on 27017 port. Now the mongod program is listening for connections on that port and so the connection from my project is no more refused.
Make a configuration file like config.js
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl' : 'mongodb://localhost:27017/cubs'
}
And require that file in your server code
var config = require('./config');
var mongoose = require('mongoose');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("Connected correctly to server");
});

Resources