NodeJS - HTTPS/HTTP Proxy Server Setup - node.js

I'm currently trying to setup an HTTP/HTTPS proxy server using NodeJS. Using the example of this gist, this is what I have.
var fs = require('fs'),
http = require('http'),
https = require('https'),
httpProxy = require('http-proxy');
var isHttps = true; // do you want a https proxy?
var options = {
https: {
key: fs.readFileSync('/home/ubuntu/key.key'),
cert: fs.readFileSync('/home/ubuntu/crt.crt')
}
};
// this is the target server
var proxy = new httpProxy.HttpProxy({
target: {
host: '127.0.0.1',
port: 11612
}
});
if (isHttps)
https.createServer(options.https, function(req, res) {
console.log('Proxying https request at %s', new Date());
proxy.proxyRequest(req, res);
}).listen(443, function(err) {
if (err)
console.log('Error serving https proxy request: %s', req);
console.log('Created https proxy. Forwarding requests from %s to %s:%s', '443', proxy.target.host, proxy.target.port);
});
else
http.createServer(options.https, function(req, res) {
console.log('Proxying http request at %s', new Date());
console.log(req);
proxy.proxyRequest(req, res);
}).listen(80, function(err) {
if (err)
console.log('Error serving http proxy request: %s', req);
console.log('Created http proxy. Forwarding requests from %s to %s:%s', '80', proxy.target.host, proxy.target.port);
});
Issue is, when I run it on my Ubuntu server, this is the error I'm getting. Kinda lost.
/home/ubuntu/prox.js:16
var proxy = new httpProxy.HttpProxy({
^
TypeError: undefined is not a function
at Object.<anonymous> (/home/ubuntu/prox.js:16:13)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
17 Jan 23:18:34 - [nodemon] app crashed - waiting for file changes before starting...

Have you tried the following, might help, this is from their git hub page.
var proxy = httpProxy.createProxyServer(options);

Related

Getting a error in my node js https server

I have built a https server and got my certs all there and it seems to find them with no issues. My my issue is that any time I run the code I am getting
var proxy = new http_proxy.HttpProxy({
^
TypeError: http_proxy.HttpProxy is not a constructor
at Object.<anonymous> (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\server.js:11:13)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
I tried to find the issue on the web but can't seem to get it to work.
Here is my code:
var http_proxy = require ('http-proxy'),
https = require('https'),
fs = require('fs');
var privateKey = fs.readFileSync("privatekey.pem").toString();
var cert = fs.readFileSync("newcert.pem").toString();
var options = {key: privateKey, cert: cert };
var proxy = new http_proxy.HttpProxy({
target:{
host: "localhost",
port: 8080
}
});
var s =https.createServer(options, function (req, res) {
console.log("Proxying!");
proxy.proxyRequest(req, res);
});
s.listen(8443);
The docs don't specify your syntax nor the library exports the module you're trying to initialize.
RTFM https://www.npmjs.com/package/http-proxy
EDIT
Even though the docs are VERY good, here's an example w/ Proxy over HTTPS node server:
var http_proxy = require ('http-proxy'),
https = require('https'),
fs = require('fs');
var privateKey = fs.readFileSync("privatekey.pem").toString();
var cert = fs.readFileSync("newcert.pem").toString();
var options = {key: privateKey, cert: cert };
var proxy = httpProxy.createServer({
ssl: {
key: privateKey,
cert
},
target: 'https://localhost:9010', // Send it anywhere
secure: true // Depends on your needs, could be false.
}).listen(443);
var s = https.createServer(options, function (req, res) {
console.log("Proxying!");
proxy.web(req, res);
});
s.listen(8443);

TypeError: server.connection is not a function in Hapi nodejs

I started working with Hapi nodejs framework. I am using "hapi#17.2.0" and here is my code in server.js to initiate application.
'use strict';
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({ port: 3000, host: 'localhost' });
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Hello, world!');
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});
After running my project with node server.js from terminal it's throwing error as given below.
/var/www/html/hello_hapi/server.js:6
server.connection({ port: 3000, host: 'localhost' });
^
TypeError: server.connection is not a function
at Object.<anonymous> (/var/www/html/hello_hapi/server.js:6:8)
at Module._compile (module.js:612:30)
at Object.Module._extensions..js (module.js:623:10)
at Module.load (module.js:531:32)
at tryModuleLoad (module.js:494:12)
at Function.Module._load (module.js:486:3)
at Function.Module.runMain (module.js:653:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
I found a solution to resolve my error. I just replaced
server.connection({ port: 3000, host: 'localhost' });
with
const server = new Hapi.Server({ port: 3000, host: 'localhost' });
Here is the description below:
According to hapi v17.0.0 they Removed support for multiple connections for a single server
The server.connection() method is replaced with options passed directly when creating a server object.
connection property is removed from all objects.
All connection methods moved to the server.
Removed support for labels and select() methods and options.
In hapi 16, there was support for server.connection(), but in hapi 17, they replaced server.connection() and instead
const Hapi = require('hapi')
const server = Hapi.server({
port:3000 || process.env.port
})
This can be used in node js.
If you are using typescript and typings, then
const server = new Hapi.server({port:3000 || process.env.port})
replace with this
const server = new Hapi.Server({
host: 'localhost',
port: 3000
})
if you are using this
server.connection({
port: 8000,
host: 'localhost'
});

Running NodeJS with TLS protocol

Generated a self-signed certificate with OpenSSL and copied the certificate & the private key to the required destination folder.
To create an HTTPS server, we require two things: an SSL certificate, and Node's built-in https module.
With Node.js installed, I tried the following JavaScript to run from the command Line
TLSServer.js
var tls = require('tls');
var fs = require('fs');
var port = 8081; //3000;
var host = '127.0.0.1'; //192.168.1.135
var options = {
key: fs.readFileSync('private-key.pem'), // /path/to/private-key.pem
cert: fs.readFileSync('certificate.pem') // /path/to/certificate.pem
};
TLSClient.js
var client = tls.connect(port, host, options, function() {
console.log('connected');
if (client.authorized) {
console.log('authorized: ' + client.authorized);
client.on('data', function(data) {
client.write(data); // Just send data back to server
});
} else {
console.log('connection not authorized: ' + client.authorizationError);
}
});
Actual Output:
cmd>node TLSServer.js
openssl config failed: error:02001005:system library:fopen:Input/output error
cmd>node TLSClient.js
openssl config failed: error:02001005:system library:fopen:Input/output error
events.js:193
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT 127.0.0.1:8081
at Object._errnoException (util.js:1031:13)
at _exceptionWithHostPort (util.js:1052:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1195:14)
What might be the reason for getting this issue:
openssl config failed: error:02001005:system library:fopen:Input/output error
httpserver.js
var fs = require('fs');
var https = require('https');
var options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('certificate.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.write("You are connected to https server");
res.end("\n hello world \n");
}).listen(8080)
https://localhost:8080
From browser I used to get the following output:
You are connected to https server
hello world
But not with TLS Client/Server. But what might be there to modify in OpenSSL config file?
Solved openssl config failed: error:02001005:system library:fopen:Input/output error by adding the path of openssl.cnf in Environment Variables -> System Variables
OPENSSL_CONF=C:\OpenSSL-Win64\bin\openssl.cnf
To validate it you can type in the shell:
echo %OPENSSL_CONF%
But still I'm getting error with TLSServer.js
cmd>node TLSServer.js
module.js:544
throw err;
^
Error: Cannot find module 'C:\Users\user\Desktop\TLSServer.js'
at Function.Module._resolveFilename (module.js:542:15)
at Function.Module._load (module.js:472:25)
at Function.Module.runMain (module.js:682:10)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:613:3

Node HTTP Server EADDRINUSE

I'm currently writing an mocha test for my project.
The test should cover the output of an ajax request and therefore I created a simple HTTP-Server with node.
This is the current code:
const http = require('http');
const server = http.createServer(function(req, res) {
res.write('test');
});
const port = 5555;
process.on('uncaughtException', function(err) {
console.log("Unhandled Exception, shutting down Server ...")
server.close();
console.log("Server closed!");
console.log(err);
process.exit(1);
});
process.on('SIGTERM', function() {
console.log("Termination called, shutting down Server ...");
server.close();
console.log("Server closed!");
process.exit(1);
});
server.listen('success', function(req, res) {
res.writeHead(200, {
"Content-Type": "application/json"
});
res.write(JSON.stringify({
success: true,
message: "Form success!"
}));
res.close();
});
server.listen('fail', function(req, res) {
res.writeHead(200, {
"Content-Type": "application/json"
});
res.write(JSON.stringify({
success: false,
message: "Form fail!"
}));
res.close();
});
server.listen(port);
console.log("Server running on Port: " + port);
Now for some reason it always throws me an EADDRINUSE error even when the port isn't used. I killed all node/nodejs processes (there weren't any), searched for the program which is using the port (lsof -i tcp:5555) which didn't send any back and even restarted the machine without any difference.
This is the output of the Terminal:
Server running on Port: 5555
Unhandled Exception, shutting down Server ...
Server closed!
{ Error: listen EADDRINUSE success
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at Server._listen2 (net.js:1249:19)
at listen (net.js:1298:10)
at Server.listen (net.js:1382:7)
at Object.<anonymous> (/home/dominik/Documents/workspace/jelly/test/test-server.js:23:8)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
code: 'EADDRINUSE',
errno: 'EADDRINUSE',
syscall: 'listen',
address: 'success',
port: -1 }
npm ERR! Test failed. See above for more details.
I tried to search for solutions already of course, but all I find is kill the server with the same commands. Thanks in advance
You are not using the http module correctly. With the statement server.listen('success',...) you are starting a UNIX socket server on the socket "success" which makes no sense.
Below is an example where the http server returns different responses based in the requested url. I recommend reading this tutorial.
const http = require('http');
const server = http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'application/json',
});
var responseBody = {};
if (req.url === '/success') {
responseBody = {
success: true,
message: "Form success!"
};
}
if (req.url === '/fail') {
responseBody = {
success: false,
message: "Form fail!"
};
}
res.write(JSON.stringify(responseBody));
res.end();
});
const port = 5555;
process.on('uncaughtException', function (err) {
console.log("Unhandled Exception, shutting down Server ...")
server.close();
console.log("Server closed!");
console.log(err);
process.exit(1);
});
process.on('SIGTERM', function () {
console.log("Termination called, shutting down Server ...");
server.close();
console.log("Server closed!");
process.exit(1);
});
server.listen(port, function () {
console.log("Server running on Port: " + port);
});
Test:
curl http://localhost:5555/success
curl http://localhost:5555/fail

NODE.JS - OpenShift 503 Service is Temporarily Unavilable: Server.js and Package.json files are fine

Project running on a Node.js Server:
I'm going crazy over here. I can't figure out why I am getting a 503 error when I have done exactly what Open Shift instructs to do.
Server.js:
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
server.listen(server_port, server_ip_address, function(){
console.log("Listening on " + server_ip_address + ",
server_port " +server_port);
});
package.json:
{
"scripts": {
"start": "supervisor server.js"
},
"main": "server.js"
}
I have gone through my logs and everything, and it says there is an issue at line 5 on server.js. How is that so? Am I going crazy, or am I missing something? The NPM modules are cleared, and the application says it is fine.
This is not a replica of another post, because I have done all of those.
Server Log Trail Error:
ReferenceError: server is not defined
at Object.<anonymous> (/var/lib/openshift/550764f6e0b8cd8a8a00007e/app- root/runtime/repo/server.js:4:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
DEBUG: Program node server.js exited with code 8
DEBUG: Starting child process with 'node server.js'
/var/lib/openshift/550764f6e0b8cd8a8a00007e/app- root/runtime/repo/server.js:4
server.listen(server_port, server_ip_address, function(){
^
I have no idea what is going on. I keep getting a server is undefined issue, and everything is done correctly from what I can see.
You have a string opened at the end of line 5 and you never close it. change it to
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
server.listen(server_port, server_ip_address, function(){
console.log("Listening on " + server_ip_address
+ ", server_port " + server_port);
});
and you should be good to go
If that is what your file actually looks like, it looks like you are missing a chunk of code:
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write("Welcome to Node.js on OpenShift!\n\n");
response.end("Thanks for visiting us! \n");
});
server.listen( port, ipaddress, function() {
console.log((new Date()) + ' Server is listening on port 8080');
});
That code is referenced from this quickstart: https://github.com/openshift-quickstart/openshift-nodejs-http-and-websocket-example/blob/master/server.js
The references server.js includes some websocket code also, but you can ignore that (unless you want to use it, that's fine too)

Resources