How to connect AWS elasticache redis from Node.js application? - javascript

How to connect AWS elasticache redis from Node.js application ?

You're connecting to Redis. The fact that it's a managed AWS service is not really that important in this respect.
So, use a Node.js package that implements a Redis client interface, for example:
redis
node-redis

You can use the package ioredis
and stablish a connection like this
const Redis = require('ioredis')
const redis = new Redis({
port: 6379,
host: 'your-redis-host',
connectTimeout: 10000 // optional
});

You can try connecting using ioredis.
var Redis = require('ioredis');
var config = require("./config.json");
const redis = new Redis({
host: config.host,
port: config.port,
password: config.password, // If you have any.
tls: {}, // Add this empty tls field.
});
redis.on('connect', () => {
console.log('Redis client is initiating a connection to the server.');
});
redis.on('ready', () => {
console.log('Redis client successfully initiated connection to the server.');
});
redis.on('reconnecting', () => {
console.log('Redis client is trying to reconnect to the server...');
});
redis.on('error', (err) => console.log('Redis Client Error', err));
//check the functioning
redis.set("framework", "AngularJS", function(err, reply) {
console.log("redis.set ", reply);
});
redis.get("framework", function(err, reply) {
console.log("redis.get ", reply);
});

Related

Ssh tunnel Node.js to MongoDB

I have installed ssh2 in order to be able to connect from my Node.js server to MongoDB. First, when I run the code provided by documentation I take this Module not found: Error: Can't resolve 'cpu-features' in 'C:\Users\chris\Desktop\abot\node_modules\ssh2\lib\protocol' and this
Module not found: Error: Can't resolve './crypto/build/Release/sshcrypto.node' in 'C:\Users\chris\Desktop\abot\node_modules\ssh2\lib\protocol'
With a little resarch I understand that this module not found errors are for optional modules and do not have some impact. Second, I am trying to connect with this code provided by the documentation:
const { Client } = require('ssh2');
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.forwardOut('my local ip', 8000, '127.0.0.1', 27017, (err, stream) => {
if (err) throw err;
stream.on('close', () => {
console.log('TCP :: CLOSED');
conn.end();
}).on('data', (data) => {
console.log('TCP :: DATA: ' + data);
}).end([
'HEAD / HTTP/1.1',
'User-Agent: curl/7.27.0',
'Host: 127.0.0.1',
'Accept: */*',
'Connection: close',
'',
''
].join('\r\n'));
});
}).connect({
host: 'ip of the mongo server',
port: ssh port,
username: 'my user name',
password: 'my password'
});
Let me note that the server is configured to connect without providing the public key.
When I am running the code, I take these messages:
Client :: ready
TCP :: CLOSED
Note number 2. I can connect with ssh tunnel through python, but now I need to connect through node also but without results.

socket is closed when trying to connect to port forwarded database

I did the port forwarding to port 54320
ssh -L 54320:<some host>:5432 ns1
I have the connection string that looks like this
postgres://<login>:<password>#localhost:54320/db_name
And I am trying to connect to node-postgres library like this
const { Client } = require('pg');
client = new Client({ connectionString: pgConnectionString });
await client.connect(err => {
if (err) {
console.error('connection error', err.stack)
} else {
console.log('connected')
}
});
However it fails with connection error Error [ERR_SOCKET_CLOSED]: Socket is closed
What is the problem? pg version is "pg": "^7.11.0",

Can't connect to local Node.js secure WebSocketServer

For testing a JavaScript / html5 application, I created a local WebSocketServer with node.js and ws package. I want to use secure websockets (wss) with SSL/TLS.
Key and certificate were create for testing purposes by OpenSSL locally (self signed certificate).
The client just tries to use the native WebSocket object to connect to the (local) https Server:
var ws = new Websocket('wss://localhost:8080');
The Problem is, no browser (Firefox, Chrome, Edge) can connect to the server and they all give me different error messages.
Firefox:
Firefox can not connect to the server at wss: // localhost: 8080 /.
Chrome:
ws_client.js:7 WebSocket connection to 'wss://localhost:8080/' failed:
Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID
Edge:
SCRIPT12017: SCRIPT12017: WebSocket Error: SECURITY_ERR, Cross zone
connection not allowed
I created the certificate and key in OpenSSL (light, newest version) like this:
openssl req -new -x509 -nodes -out server.crt -keyout server.key
(source)
I checked almost every question about this (and similar) topics, e.g. this question, but none of them could provide a solution.
Please do not mark this question as a duplicate, because all similar questions contain slightly different problems!
Server Code:
var fs = require('file-system');
var pkey = fs.readFileSync('server.key', 'utf8');
var crt = fs.readFileSync('server.crt', 'utf8');
var credentials = { key: pkey, cert: crt };
var https = require('https');
var httpsServer = https.createServer(credentials);
httpsServer.listen(8080);
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({
server: httpsServer
});
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
ws.send('reply from server : ' + message)
});
});
I tried another code as server, but same errors occur:
const WebSocketServer = require('ws').Server;
var fs = require('file-system');
var ws_cfg = {
ssl: true,
port: 8080,
ssl_key: 'server.key',
ssl_cert: 'server.crt'
};
var processRequest = function(req, res) {
console.log('Request received');
};
var httpServ = require('https');
var app = httpServ.createServer({
key: fs.readFileSync(ws_cfg.ssl_key, 'utf8', (error) => {
console.log('Error reading file');
}),
cert: fs.readFileSync(ws_cfg.ssl_cert, 'utf8', (error) => {
console.log('Error reading file');
})
}, processRequest).listen(ws_cfg.port, function(){
console.log('Server running');
});
var wss = new WebSocketServer( {server: app, port: 8080, host: 'localhost', domain: 'localhost'} );
wss.on('connection', function (ws) {
console.log('Connected to a client');
ws.on('message', function (message) {
console.log('MSG received: ' + message);
});
});
There's one more thing. Always, if I add a console.log(wss); to the server Code, the output looks something like this:
WebSocketServer {
domain: null,
...some more stuff...
...cert key etc....
host: null,
path: null,
port: null } }
host, domain and port is set to null. I tried everything to set it to localhost:8080, but nothing worked out. I think this could be the source of all Problems, but can't find a way. If anyone knows an answer to this question, I would highly appreciate it.
(Using the insecure 'ws' protocol ('ws://localhost:8080') in order to connect to local node.js http server works, but I want to test the app as realistic as possible and use a secure Connection.)
-- This is not an answer, just my workaround --
For anyone having the same problems, here is what I did:
Server Code should be:
const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
const server = new https.createServer({
cert: fs.readFileSync('localcert.cert'), //what ever you're files are called
key: fs.readFileSync('localkey.key')
});
const wss = new WebSocket.Server({ server }); // !
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('MSG received: %s', message);
});
ws.send('Hi to client');
});
server.listen(8080);
Only working in Google Chrome for now, can still not connect in Firefox.
enter chrome://flags/#allow-insecure-localhost in Google Chrome and enable.
Try to add the self-signed certificate or the generated CA to be trusted on the system that you are using.

Avoid creating onMessage function per WS client

Following ws's instructions to create a WebSocket server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
An onMessage callback named incoming is created for every client, am I right?
Imagine having two million clients. This code would create two million functions. Is there a way to avoid this? Something like this would be wonderful:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('message', function incoming(ws, message) {
// Access to ws object
console.log('received: %s', message);
});
How about:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
function handleMessage(message) {
console.log('received: %s', message);
}
wss.on('message', handleMessage);

Connecting to MSSQL server with Sequelize

Using the following tedious code, I can successfully connect to an Azure SQL Server.
const Connection = require('tedious').Connection;
const connection = new Connection({
userName: '[USER]',
password: '[PASSWORD]',
server: '[HOSTNAME]',
options: {encrypt: true}
});
connection.on('connect', (err) => {
if (err) {
console.log('error connecting', err);
} else {
console.log('connection successful');
}
});
However, using what should be the equivalent Sequelize code, I get a connection timeout error.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('[DBNAME]', '[USER]', '[PASSWORD]', {
dialect: 'mssql',
host: '[HOSTNAME]',
dialectOptions: {
encrypt: true
}
});
sequelize.authenticate().then((err) => {
console.log('Connection successful', err);
})
.catch((err) => {
console.log('Unable to connect to database', err);
});
Any thoughts?
Using: sequelize 3.29.0, tedious 1.14.0, SQL Server v12
I was getting below error
SequelizeConnectionError: Server requires encryption, set 'encrypt' config option to true.
I tried it out with Azure SQL Database and below way is working for me.
const sequelize = new Sequelize('DB Name', 'Username', 'Password', {
host: 'Host',
dialect: 'mssql',
dialectOptions: {
options: {
encrypt: true,
}
}
});
If you're trying it out with Azure SQL Database, you might also want to specify a longer request timeout value:
[...]
dialectOptions: {
requestTimeout: 30000 // timeout = 30 seconds
}
[...]
I tried your Sequelize code and it works fine. So you might need to add Client IP address to allow access to Azure SQL Server. To do this, go to the Azure portal, click on All Resources, select your SQL server, click on Firewall in the SETTINGS menu.
Your client address is conveniently included in the list, so you can just click on Add client IP followed by Save. When you run your code now, it should connect.
if you are using sql server management studio then simply replace dialect:'mysql' with dialect:'mssql':
const sequelize = new Sequelize('DB Name', 'Username', 'Password', {
host: 'Host',
dialect: 'mssql',
dialectOptions: {
options: {
encrypt: true,
}
}
});

Categories