In my node web server, I am using a the npm module redis.
when I run my code...
const client = redis.createClient();
client.on("error", function (err) {
console.log("Error " + err);
});
client.hmset(["key", "test keys 1", "test val 1", "test keys 2", "test val 2"], function (err, res) {});
I get an error:
Error Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
I don't have a redis database installed. Do I need that?
If not, anything I have missed in my code?
Yes, you need to install Redis and ensure the server is running. This is a link to the official page for downloading the redis.
In your application code, you need to ensure you are connecting to Redis server with the right port and host address. By default, Redis server should be running on 127.0.0.1:6379 and that is where redis.createClient would try to connect to by default. If your Redis server is running on another port or host, then you need to specify those details when connecting e.g:
redis.createClient({
host: '<the host where redis is running>',
port: '<the port where redis is running>'
});
You can check here for more info on the options you can provide when connecting to Redis server with redis.createClient.
Related
I have a redis server which is working fine in my local but in ubuntu server is not working can someone gives the comment for installing redis in server
it is not working even with docker it is working only while i am running in local
const redis=require('redis');
var redisClient:any;
(async () => {
try {
redisClient = redis.createClient({ socket: { port: 6379 } });
await redisClient.connect();
// const redisClient = redis.createClient({
// port:"6379",
// host:'redis-service'
// });
redisClient.on('connect',()=>{
console.log('server connected to redis')
})
redisClient.on('ready',()=>{
console.log('Client Connect to redis and ready to use')
})
redisClient.on('error',(err:any)=>{
console.log(err)
})
redisClient.on('end',()=>{
console.log('Server disconnected from redis')
})
process.on('SIGINT',()=>{
redisClient.quit()
})
console.log('connected');
} catch (err) {
console.error(err)
}
})()
export{
redisClient
};
Make sure that Redis is not already running on the server. You can check this by running the command ps aux | grep redis. If Redis is running, you should see a line with the redis-server process.
Confirm that Redis is properly installed on your server by running redis-cli ping. If Redis is installed and running, it should return "PONG"
Check the Redis configuration file (redis.conf) and ensure that the IP and port settings match the settings on your local machine.
Make sure that the Redis server has the necessary permissions to access its data directory and that the correct ownership and permissions are set on its files.
Verify that the firewall rules on the server allow incoming connections on the Redis port (usually 6379)
Check for any compatibility issues between the version of Redis that you're running on your local machine and the version of Redis that's running on the Ubuntu server. If there's a version mismatch, it may be necessary to upgrade or downgrade one of the installations.
Try to run the Redis server with verbose output by running the command redis-server -v, this can give you some more information about the errors that are causing the server to fail.
Look at Redis log files, usually located in /var/log/redis for further clues about the cause of the problem.
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
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.
I am facing an issue when trying to connect to mqtt broker, I have installed the mosquitto and given two ports(1883,8883) as a listener in the mosquitto.conf file. When I try to run the code for connect from node.js for mqtts on port 8883 I get below error
Error: read ECONNRESET
and on mosquitto
socket error on client <unknown> disconnecting
When I try to publish a message using MQTT.fx it successfully publish the mesasge on port 8883
Below is my code
const config = {
endpoint: 'mqtts://192.168.0.0',
topic: 'test/topic/local',
payload: {message: 'HelloWorld'},
}
mqtt.connect(config.endpoint, {
clientId: 'some id',
})
Are there some configurations needs to be done?
mqtts is the tls version of mqtt , to use it you will need to either supply certs to match the backend or configure it not to validate if they are self signed.
to disable validation add this to your connect
rejectUnauthorized: false
be aware that doing this will prevent your client from being able to validate the backend safely, you should never do this in production.
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.