Create HTTPS client in NodeJS - javascript

I've been having a heck of a time figuring out how to use Node.js (v0.3.8) to securely connect to an HTTP server. I have the following code:
var http = require("http");
var client = http.createClient(443, host, /* secure= */ true);
var request = client.request("GET", relativeUrl, { host: host });
When I run it, I get:
node.js:116
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Parse Error
at Client.onData [as ondata] (http.js:1287:27)
at Client._onReadable (net.js:648:27)
at IOWatcher.onReadable [as callback] (net.js:156:10)
I've been Googling for answers for the past half hour, and have read the documentation at http://nodejs.org/ . What am I missing?

It turns out I was using an old version of the Node documentation, which didn't include a reference to the https module. Referring to the current docs, I found http://nodejs.org/docs/latest/api/https.html#https_https_get_options_callback, which provides an example:
https.get({ host: 'encrypted.google.com', path: '/' }, function (res) { … });

If you are using node.js as a client you should be able to simply substitute http for https.
That is according to the following website
https://github.com/danwrong/Restler/
"Transparently handle SSL (just specify https in the URL)"

Related

Why does ioredis client timeout when keep-alive is enabled?

I have been getting the following error, when my script stays idle for sometime. I cannot understand the reason for this.
error: [ioredis] Unhandled error event:
error: Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
error: [ioredis] Unhandled error event
error: Error: read ETIMEDOUT
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
I initialize my redis client as :
let redis = require("ioredis");
redis = Promise.promisifyAll(redis);
const redis = new redis({
host: "my hostname",
port: 6379,
password: "some password"
});
and I am using ioredis client.
Does anyone know the reason for this? The keep-alive is already enabled by default as suggested here https://github.com/luin/ioredis/blob/master/API.md
I want the client to never timeout and reconnect if the timeout occurs. I am using Redis service by azure.
We have an entire document that covers this topic: Troubleshoot Azure Cache for Redis timeouts
If using the StackExchange.Redis Client the best practice of using the following pattern is suggested:
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
return ConnectionMultiplexer.Connect("cachename.redis.cache.windows.net,abortConnect=false,ssl=true,password=...");
});
public static ConnectionMultiplexer Connection
{
get
{
return lazyConnection.Value;
}
}
In the case of ioredis, you can set a client property: [options.lazyConnect]
You will also want to look at any retry methods available with your client. I hope this helps.

How do I properly set up the Cassandra client in Javascript?

Right now, I'm running a docker with Cassandra on it. I have a javascript file that sits outside the docker that needs to connect to Cassandra. I've found a node package that interfaces w/ JS, called cassandra-driver. However, with the following code:
var cassandra = require('cassandra-driver');
var PlainTextAuthProvider = cassandra.auth.PlainTextAuthProvider;
const client = new cassandra.Client({
contactPoints: ['127.0.0.1:9042'],
localDataCenter: '127.0.0.1',
keyspace: 'wasabi_experiments',
authProvider: new PlainTextAuthProvider('cassandra', 'cassandra')
});
I get
(node:17836) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): NoHostAvailableError: All host(s) tried for query failed. First host tried, 127.0.0.1:9042: ArgumentError: localDataCenter was configured as '127.0.0.1', but only found hosts in data centers: [datacenter1]. See innerErrors.
(node:17836) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): NoHostAvailableError: All host(s) tried for query failed. First host tried, 127.0.0.1:9042: ArgumentError: localDataCenter was configured as '127.0.0.1', but only found hosts in data centers: [datacenter1]. See innerErrors.
How can I get this to work?
Your problem is that you're using the 127.0.0.1 as value for localDataCenter parameter, but it should be set not to the address of the machine, but to the name of the Cassandra data center - in your case this is datacenter1. Change the value of that parameter to datacenter1, and it will start to work.
It would be:
const { Client, auth } = require('cassandra-driver');
const client = new cassandra.Client({
contactPoints: ['127.0.0.1:9042'],
localDataCenter: 'datacenter1', // here is the change required
keyspace: 'wasabi_experiments',
authProvider: new auth.PlainTextAuthProvider('cassandra', 'cassandra')
});
client.connect();
P.S. I recommend to read documentation for Node.js driver, and also "Developing applications with DataStax drivers" guide.
try first with a Cassandra client, ensure Cassandra is working properly and you can access it. After that try with the code.
Also you can try to access the 127.0.0.1:9042 using telnet or netcat to see if the port is open and listening. You can use netstat too for this task.

How to connect a node server without browser

I am using node-jet library as message broker using a websocket.
In my code, there is a deamon and there are peers connect to it. In libary documentation its says peers can connect either by websocket or trivial tcp connection (never used second one before)
Here is server code I try to connect (its running when I try to connect)
https://github.com/lipp/node-jet/blob/master/examples/todo/todo-server.js
Everything works fine if I run my peer javascript inside a browser however, I am not able to run it from console.
var peer3 = new jet.Peer({
url: 'wss://217.78.109.178:8090'
//url: (window.location.protocol === 'http:' ? 'ws://' : 'wss://') +
window.location.host
})
documentation says it will use trivial tcp if no url provided so I also tried this. Again works in browser but not standalone. Any idea ? how can I solve this problem ?
var peer3 = new jet.Peer({
})
$ node Peer.js
Peer: connect failed { no remote stack
name: 'jet.ConnectionClosed',
message: '',
url: 'https://github.com/lipp/node-
jet/blob/master/doc/peer.markdown#jetconnectionclosed'
}

Node JS VPN connect to endpoint

I hope you can help!
I have setup and Amazon echo applcation, the application makes a request to and AWS EC2 instance and gets JSON data as a response, this is working as expected however the use case for the final application is to connect to a private IP sending paramaters to an API to return the same JSON DATA.
for many reasons sadly I cannot share any of the endpoint information.
I need my NODE.js Application to make a request to the private IP over a VPN connection, Im currently using OPENVPN to make local requests to the endpoint.
I have looked at node packages to see if this is possible but I cannot seem to find one, except for this package here
https://www.npmjs.com/package/node-openvpn
This package is has a dependancy thats fails to download, so i got the node_module manually but Im getting an error when i try to execute the code
var openvpnmanager = require('node-openvpn');
var opts = {
host: 'xx.xx.xx.xx', // normally '127.0.0.1', will default to if undefined
port: 443, //port openvpn management console
timeout: 1500, //timeout for connection - optional, will default to 1500ms if undefined
logpath: 'log.txt' //optional write openvpn console output to file, can be relative path or absolute
};
var auth = {
user: '*******',
pass: '*******',
};
var openvpn = openvpnmanager.connect(opts)
openvpn.on('connected', function() { //will be emited on successful interfacing with openvpn instance
openvpnmanager.authorize(auth);
});
openvpn.on('console-output', function(output) { //emits console output of openvpn instance as a line
console.log(output)
});
openvpn.on('state-change', function(state) { //emits console output of openvpn state as a array
console.log(output)
});
// openvpnmanager.getLog(console.log) //get all console logs up to this point
// and finally when/if you want to
// openvpnmanager.disconnect();
openvpn.on('disconnected', function() { //emits on disconnect
openvpnmanager.destroy() //finally destroy the disconnected manager
});
this just gives me an error
Unhandled rejection TypeError: Cannot read property 'writable' of undefined
at Telnet.exec (C:\Users\user\Desktop\alexa- po\node_modules\node-openvpn\node_modules\telnet-client\lib\telnet- client.js:90:24)
If anybody has any suggetions on how to make this possible I would be very grateful.

Node js + Sails js + websocket app crashing every few hours

I am having a problem similar to socket.io issue using sails.js. Every once in a while (once per day, or even few hours, it varies), a visitor to the web site/app will crash Node, seemingly due to the way his websocket client tries to connect. Anyway, here's the crash log:
debug: Lowering sails...
/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/express/node_modules/connect/lib/utils.js:216
return 0 == str.indexOf('s:')
^
TypeError: Cannot call method 'indexOf' of undefined
at exports.parseSignedCookie (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/express/node_modules/connect/lib/utils.js:216:19)
at Manager.socketAttemptingToConnect (/Volumes/Two/Sites/lsdfinder/node_modules/sails/lib/hooks/sockets/authorization.js:35:26)
at Manager.authorize (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:910:31)
at Manager.handleHandshake (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:786:8)
at Manager.handleRequest (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:593:12)
at Server.<anonymous> (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:119:10)
at Server.EventEmitter.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2076:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:120:23)
at Socket.socket.ondata (http.js:1966:22)
9 Oct 10:42:24 - [nodemon] app crashed - waiting for file changes before starting...
In config/sockets.js, authorization is set to true. Not sure what else to do, where to fix this. Any suggestions? I can read the Sails docs too, but this appears to be a problem in Express/Connect, no? Thanks.
...René
The problem is that once every so often, a client will connect that has no cookies. Sails.js is using util.parseSignedCookie() from Connect without checking for errors, and therefore an error is thrown. This is what it looks like in Sails:
if (handshake.headers.cookie) {
handshake.cookie = cookie.parse(handshake.headers.cookie);
handshake.sessionID = parseSignedCookie(handshake.cookie[sails.config.session.key], sails.config.session.secret);
}
If you take a look into the cookieParser() middleware of Connect, you can see error checking is required:
if (cookies) {
try {
req.cookies = cookie.parse(cookies);
if (secret) {
req.signedCookies = utils.parseSignedCookies(req.cookies, secret);
req.signedCookies = utils.parseJSONCookies(req.signedCookies);
}
req.cookies = utils.parseJSONCookies(req.cookies);
} catch (err) {
err.status = 400;
return next(err);
}
}
I've created a Gist here that fixes the problem, and will submit a pull request to Sails.js when I have the time. The Gist uses Connect's cookieParser() middleware to automatically handle errors. If you want to use this, modify this file in your modules folder:
node_modules/sails/lib/hooks/sockets/authorization.js
If you are doing a crossdomain request, you could turn off authorization.
In *site_dir/config/sockets.js* set authorization to false. One way of doing it. You can also call your api with something like this
bash
**http://localhost:1337?cookie=smokeybear**
Its is in the comments on the sockets.js file.

Categories

Resources