Node HTTP Server EADDRINUSE - node.js

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

Related

connect EADDRINUSE: cannot use node.js tcp client localPort after reconnecting within 30 seconds?

I have created a tcp server and a tcp client.
In my tcp client, I have specified the localPort because I want to use some specific ports in case of reconnection.
Below is my tcp server and client's code
TCP SERVER
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
socket.on('error', function(err){
console.log('on socket error', err);
})
});
server.on('error', function(err){
console.log('on error',err);
})
server.listen(1337, '127.0.0.1');
TCP CLIENT
var net = require('net');
var client = new net.Socket();
client.connect({port: 1337, host: '127.0.0.1', localPort: 10002}, function() {
console.log('Connected');
client.write('Hello, server! Love, Client.');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
client.on('error', function(err) {
console.log('error in connection',err);
});
I have this server and client in two separate files.
If I run the server, and then run the client for the first time, everything works fine.
But as soon as I re-run(reconnect) the client, it gives me an error
{ Error: connect EADDRINUSE 127.0.0.1:1337 - Local (0.0.0.0:10002)
at internalConnect (net.js:964:16)
at defaultTriggerAsyncIdScope (internal/async_hooks.js:281:19)
at net.js:1062:9
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickCallback (internal/process/next_tick.js:181:9)
at Function.Module.runMain (module.js:696:11)
at startup (bootstrap_node.js:204:16)
at bootstrap_node.js:625:3
errno: 'EADDRINUSE',
code: 'EADDRINUSE',
syscall: 'connect',
address: '127.0.0.1',
port: 1337 }
It works fine if I retry after around 30 seconds.
Does net in nodejs have a TIMEOUT of not using the same localPort for 30 seconds?
If it is so, can we reduce it or manage it somehow?

How do I communicate between microservices?

I have the following code in one microservices that calls another:
axios.get('http://localhost:4210/usermicroservice/heartbeat')
.then(function(resp) {
console.log('USER HEARTBEAT CALLED ')
})
.catch(function(error) {
console.log('USER HEARTBEAT ERROR ', error)
})
In the called microservice I have the following code:
server.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
next();
})
server.get('/usermicroservice/heartbeat', (req, res) => {
console.log('\n*** USER MICROSERVICE CALLED ***')
res.json({});
})
const PORT = 4210;
server.listen(PORT, () => {
console.log(`hsupp01 UserMicroservice server running on port: ${PORT}`)
})
I get the following error:
{ Error: connect ECONNREFUSED 127.0.0.1:4210
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1097:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 4210,
I am able to accessed the called microservice from Postman using the same url:
http://localhost:4210/usermicroservice/heartbeat
The error message does not capture the problem but the code below had to be executed within an asynchronous block.
axios.get('http://localhost:4210/usermicroservice/heartbeat')
.then(function(resp) {
console.log('USER HEARTBEAT CALLED ')
})
.catch(function(error) {
console.log('USER HEARTBEAT ERROR ', error)
})

Can't get node app to run on openshift, Error: listen EACCES

I have been trying to fix this for hours, with endless googling, I try to start the app, go to the url and see a 503 Service Unavailable error, I then cd into app-root/repo, try to manually start server.js, and get the following:
[my-app-url.rhcloud.com repo]\> node server.js
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
Connecting to server
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:901:11)
at Server._listen2 (net.js:1039:14)
at listen (net.js:1061:10)
at net.js:1143:9
at dns.js:72:18
at process._tickCallback (node.js:415:13)
at Function.Module.runMain (module.js:499:11)
at startup (node.js:119:16)
at node.js:902:3
This is driving me insane, all I'm trying to do is a simple api, and it works perfectly in my local environment.
Thank you.
Already another program or instance of this program is running on same port.
run - sudo netstat -tapen | grep ":<<your given port>>"
and then kill the process.
Then try to run the server...
Thanks
You need to bind to the OPENSHIFT_NODEJS_IP, i see you are only binding to the correct port, not the ip also: https://developers.openshift.com/en/node-js-getting-started.html
https://github.com/openshift-quickstart/openshift-nodejs-http-and-websocket-example/blob/master/server.js#L1
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var WebSocketServer = require('ws').Server
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');
});
wss = new WebSocketServer({
server: server,
autoAcceptConnections: false
});
wss.on('connection', function(ws) {
console.log("New connection");
ws.on('message', function(message) {
ws.send("Received: " + message);
});
ws.send('Welcome!');
});
console.log("Listening to " + ipaddress + ":" + port + "...");

Socket hang up on http.request to a Node.js MongoDb server

In my local pc I've set up a Node.js proxy server who makes request to a node.js RESTful MongoDb server, one is at port 8080 and the proxy at port 3000.
I can see in the RESTful server log that all the queries are sent back correctly to the proxy, but the proxy hang up throwing this error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (http.js:1472:15)
at Socket.socketOnEnd [as onend] (http.js:1568:23)
at Socket.g (events.js:180:16)
at Socket.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
this is how I built my proxy request :
var proxy = function(req, res, next) {
try {
var options = mapRequest(req);
var dbReq = http.request(options, function(dbRes) {
var data = "";
res.headers = dbRes.headers;
dbRes.setEncoding('utf8');
dbRes.on('data', function(chunk) {
data = data + chunk;
});
dbRes.on('end', function() {
res.header('Content-Type', 'application/json');
res.statusCode = dbRes.statusCode;
res.httpVersion = dbRes.httpVersion;
res.trailers = dbRes.trailers;
res.send(data);
res.end();
});
});
dbReq.end(JSON.stringify(req.body));
} catch (error) {
console.log('ERROR: ', error.stack);
res.json(error);
res.end();
}
};
and these are the options sent to the MongoDB server:
{
"hostname":"127.0.0.1",
"path":"//databases/db1/collections/documents?apiKey=134557676&l=5&sk=0",
"method":"GET",
"port":"8080",
"headers":{
"host":"127.0.0.1",
"connection":"keep-alive",
"accept":"application/json, text/plain ",
"x-xsrf-token":"VPDlgN2iMWU2IXPIPH0aiwS5",
"user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36",
"dnt":"1",
"referer":"http://localhost:3000/documents",
"accept-encoding":"gzip,deflate,sdch",
"accept-language":"it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4",
"cookie":"XSRF-TOKEN=VPDlgN2iMWU2IXPIPH0aiwS5; connect.sess=s%3Aj%3A%7B%22passport%22%3A%7B%22user%22%3A%225298bfa9e4b070e1c60fd84f%22%7D%2C%22_csrf%22%3A%22VPDlgN2iMWU2IXPIPH0aiwS5%22%7D.wc85bNSpJIl7KnCHOUXiG5V2e7SI9XR9EctByTtqhu4"
}
}
I found a solution replacing http.request() withhttp.get(), apparently the socked hang up because the socket did not sent the connection end event within the timeout period.
A similar issue here: NodeJS - What does "socket hang up" actually mean?

NodeJS - HTTPS/HTTP Proxy Server Setup

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);

Resources