Getting "failed to start accepting connection" while deploying my app into bluemix - node.js

Hi Am facing "failed to start accepting connection" error while pushing or deploying my app to bluemix. Can any help me in that.... my code snippet as given below:
var express = require('express');
app = express();
var ibmbluemix = require('ibmbluemix')
var ibmdb = require('ibm_db');
var http = require('http');
var url = require('url');
var logger = ibmbluemix.getLogger();
var PORT = (process.env.VCAP_APP_PORT || 8000);
var HOST = (process.env.VCAP_APP_HOST || 'localhost');
var queryData = null;
var serviceName = 'SQLDB';
if (process.env.VCAP_SERVICES) {
var env = JSON.parse(process.env.VCAP_SERVICES);
db2 = env['sqldb'][0].credentials;
}
else{
console.error("INFORMATION FOR DB CONNECTION NOT FOUND");
}
var dbConnection = "DRIVER={DB2};DATABASE=" + db2.db + ";UID=" + db2.username + ";PWD=" + db2.password + ";HOSTNAME=" + db2.hostname + ";port=" + db2.port;
console.log("Connection String: " + dbConnection);
http.createServer(function(request, response) {
console.log('Creating the http server');
ibmdb.open(dbConnection, function(err, conn) {
if (err) {
response.send("error occurred " + err.message);
}
else {
console.log('before select');
conn.query("SELECT FULL_NAME, PASSWORD, SHORT_ID FROM USER02130.USER_DETAILS", function(err, rows, moreResultSets) {
console.log('Connection result error '+err);
console.log('no of records is '+rows.length);
response.writeHead(200, { 'Content-Type': 'application/json'});
response.write(JSON.stringify(rows));
response.end();
});
}
}).listen(PORT, HOST);
Can anyone help me in this, Thanks in advance

There are a few syntactical errors in your snippet (missing closing brackets etc). Try using this instead:
var express = require('express');
app = express();
var ibmbluemix = require('ibmbluemix')
var ibmdb = require('ibm_db');
var http = require('http');
var url = require('url');
var logger = ibmbluemix.getLogger();
var PORT = (process.env.VCAP_APP_PORT || 8000);
var HOST = (process.env.VCAP_APP_HOST || 'localhost');
var queryData = null;
var serviceName = 'SQLDB';
if (process.env.VCAP_SERVICES) {
var env = JSON.parse(process.env.VCAP_SERVICES);
var db2 = env['sqldb'][0].credentials; // missed declaration
}
else{
console.error("INFORMATION FOR DB CONNECTION NOT FOUND");
}
var dbConnection = "DRIVER={DB2};DATABASE=" + db2.db + ";UID=" + db2.username + ";PWD=" + db2.password + ";HOSTNAME=" + db2.hostname + ";port=" + db2.port;
console.log("Connection String: " + dbConnection);
http.createServer(function(request, response) {
console.log('server request'); // does not create a server on every request
ibmdb.open(dbConnection, function(err, conn) {
if (err) {
response.send("error occurred " + err.message);
}
else {
console.log('before select');
conn.query("SELECT FULL_NAME, PASSWORD, SHORT_ID FROM USER02130.USER_DETAILS", function(err, rows, moreResultSets) {
console.log('Connection result error '+err);
console.log('no of records is '+rows.length);
response.writeHead(200, { 'Content-Type': 'application/json'});
response.write(JSON.stringify(rows));
response.end();
});
}
}) // missed closing brackets
}).listen(PORT, HOST);
console.log("Server running at "+HOST+" on port "+ PORT);
Node.js is very easy to set up locally, get it here. Running it locally can help you identify many problems, such as syntactical error.
Hope it helps!

cf logs <app name> --recent
This command will give you the logs which will show you where your syntax errors were.

It's great that you figured it out, but for future reference, the “failed to start accepting connection” error usually means the code threw an exception during initialization before calling http.createServer(...).listen(port, host). Try adding the code below prior to the call to listen(...)
process.on('uncaughtException', function (err) {
console.log(err);
});
Your console logs will then include a helpful stack trace if the startup code fails for an unforeseen reason instead of receiving the default "app crashed" message.
Still stuck? Pat Mueller offers other helpful suggestions in Node.js debugging starts with better logging! and David Clements' Node.js tips #1: develop debugging techniques offers more advanced debugging tips, e.g., function de-anonymizing.

Related

Node.js send Server input to Client. Warning about memory leak. What is my mistake? And how does node.js run code?

Server:
var net = require('net');
var stdin = process.openStdin();
var client_list = [];
var server = net.createServer(function(connection) {
//console.log('client connected');
connection.on('error', function(e){
if(e.code == 'ECONNRESET'){
console.log('Client dissconeccted');
}
});
//connection.write('Hello World!\r\n');
stdin.addListener("data", function(d) {
// note: d is an object, and when converted to a string it will
// end with a linefeed. so we (rather crudely) account for that
// with toString() and then trim()
console.log("you entered: [" + d.toString().trim() + "]");
connection.write(d.toString().trim());
});
connection.pipe(connection);
});
server.listen(9999, function() {
console.log('server is listening');
});
Client:
var net = require('net');
var HOST = 'localhost';
var PORT = 9999;
//var client = new net.Socket();
var client = net.connect(PORT, HOST, function(){
console.log('connected to server! ' + HOST + ':' + PORT);
//client.write('I am Superman');
});
client.on('data', function(data) {
var data = data.toString();
console.log(data);
//If data starts with JS add injection functionallity
if (data === "END"){
client.end();
console.log("ENDING!")
}
else if (data === "poo"){
console.log("HOLY SHIT!")
}
});
//Keep trying to connect!
client.on('error', function(e) {
console.log('Parent connection error');
//client.end();
client.connect(PORT, HOST);
});
client.on('end', function() {
console.log('disconnected from server');
});
/*var client = net.connect({port: 8080}, function() {
console.log('connected to server!');
});*/
So what happens is that it keeps adding listeners(?) and warns me at 11 listeners with the message:
"Possible EventEmitter memory leak detected. 11 data listeners added.
Use emitter.setMaxListeners() to increase limit".
Why is this? I have tried fixing this by moving stdin.addListener() but it either doesn't take the input at all or the problem persists. Am I onto something? And how is code run in node, is it a loop?
Thanks in advance!
Have run both the client and server scripts. I can't reproduce the error message that you're getting. I'm running the code on Ubuntu - nodejs 6.9.5, npm 5.4.2. Could you post the contents of your package.json file?
Update: had a look online. seems like a known old bug in Node. https://github.com/nodejs/node-v0.x-archive/issues/5108

File-upload error using Cordova FileTransfer to NodeJS

I'm currently working on a Phonegap app, and I would like users to be able to upload any file to my NodeJS server.
I've looking all around the web but I just can't get anything to work...
Here is the code I'm using for the Phonegap controller:
$scope.open = function()
{
navigator.camera.getPicture(upload,
function(message)
{
alert('get picture failed');
},
{
quality: 50,
destinationType: navigator.camera.PictureSourceType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
mediaType: navigator.camera.MediaType.ALLMEDIA
});
}
var win = function (r) {
$scope.log = "Code = " + r.responseCode;
$scope.log2 = "Response = " + r.response;
$scope.log3 = "Sent = " + r.bytesSent;
$scope.$digest();
}
var fail = function (error) {
$scope.log = "An error has occurred: Code = " + error.code;
$scope.log2 = "upload error source " + error.source;
$scope.log3 = "upload error target " + error.target;
$scope.$digest();
}
function upload(fileURI)
{
$scope.log = fileURI;
$scope.$digest();
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
options.chunkedMode = false;
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(fileURI, "http://192.168.192.111:2999/upload", win, fail, options);
}.
Here is the current code for the NodeJS server, have tried a lot of different things, all without success:
var express = require('express');
var http = require('http').Server(express);
var io = require('socket.io')(http);
var fs = require('fs');
var multer = require('multer');
var app = new express();
app.post('/upload', multer({dest: './uploads/'}).single('upl'), function(req, res)
{
console.log(req.body);
console.log(req.file);
})
http.listen(2999, function(){
console.log('listening on *:2999');
});
In the app I used to get errors that FileUploadOptions etc weren't defined, but I fixed that by adding them to the cordova project.
Furthermore, I use ionic 1, if that helps anyone out.
I do keep constantly getting the error code 1 (upload error source), even though I selected a real file and I saw that the link was correct (something like /storage/0/emulated/Downloads on my Android device).
Also, sometimes it gives me error 3 as well (upload target source), some sort of server not found issue I think.
Is there something obvious I'm doing wrong and how would I be able to fix it? Is there a handier way, since I eventually want to link this to a MySQL database.
Thanks in advance!
Well found my answer (a while ago, this is for people stumbling across this post).
You can first try whether your JS works by changing the server to https://posttestserver.com/post.php. If you see an upload appearing there, there's a problem with the server.
The problem with me was that I didn't let Apache through the firewall at all, so uploads from anything besides my PC would fail...
var express=require('express');
var bodyParser=require('body-parser');
var formidable = require('formidable');
var util = require('util');
var app=express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var path=require('path');
var mysql =require('mysql');
var fs=require('fs');
app.use('/public',express.static(path.join(__dirname, 'public')));
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password : '',
port : 3306, //port mysql
database:'xxxxx'
});
app.post('/data', function(req, res) {
// create an incoming form object
var form = new formidable.IncomingForm(),
files = [],
fields = [];
// specify that we want to allow the user to upload multiple files in a single request
form.multiples = true;
// store all uploads in the /uploads directory
form.uploadDir = path.join(__dirname, '/public/images/uploads');
// every time a file has been uploaded successfully,
// rename it to it's orignal name
form.on('file', function(field, file) {
if (path.extname(file.name)=='') {
extension='.jpg';
}
else{
extension=path.extname(file.name);
}
var oldpath = file.path;
form.uploadDir = path.basename(file.name,extension).concat((Math.random()* 100),extension);
var newpath = './public/images/uploads/'+ path.basename(file.name,extension).concat((Math.random()* 100),extension);
//fs.rename(file.path, path.join(form.uploadDir, file.name));
fs.rename(oldpath, newpath);
});
form.on('field', function(field, value) {
fields[field] = value;
});
// log any errors that occur
form.on('error', function(err) {
console.log('An error has occured: \n' + err);
});
// once all the files have been uploaded, send a response to the client
//Call back at the end of the form.
form.on('end', function () {
res.writeHead(200, {
'content-type': 'text/plain'
});
res.write('received the data:\n\n');
// console.log(fields.name+'-'+fields.nickname);
var values={
name:fields.name,
nickname:fields.nickname,
email:fields.email,
password:fields.password,
dob:fields.dob,
gender:fields.gender,
phoneno:fields.phone
};
connection.query('INSERT INTO users SET ?', values, function(err,req,res){
if(err){
console.log('Connection result error '+err);
}
else{
console.log('Success');
}
});
res.end();
});
// parse the incoming request containing the form data
form.parse(req);
});
//app.use(app.router);
app.listen(5000);

_http_server.js:192 throw new RangeError(`Invalid status code: ${statusCode}`);

This is my code:
var express = require('express');
var http = require('http');
var redis = require('redis');
var url = require('url');
var client = redis.createClient().setMaxListeners(0);
var app = express();
app.set('port', 3000);
app.get('/*', function(req, res) {
var key = url.parse(req.url).pathname;
client.on('connect', function() {
console.log('connected to redis!');
});
client.get(key, function(err, reply) {
if( reply == null) {
client.set(key, 1);
client.expire(key, 300);
res.send('1');
}
else {
client.incr(key, function(err, reply) {
console.log('increment value: ' + reply);
res.sendStatus(reply);
});
}
});
});
http.createServer(app).listen(app.get('port'), function() {
console.log('listening');
});
This is my output when I run the file ($ node test.js):
I tried this on my ubuntu machine and it perfectly works. This is what I get on my mac. Could someone explain me why this is happening. Any help would be appreciated.
listening
increment value: 2
_http_server.js:192
throw new RangeError(`Invalid status code: ${statusCode}`);
^
RangeError: Invalid status code: 2
at ServerResponse.writeHead (_http_server.js:192:11)
at ServerResponse._implicitHeader (_http_server.js:157:8)
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:559:10)
at ServerResponse.send (/Users/sharath/webapps/docker/node_modules/express/lib/response.js:209:10)
at ServerResponse.sendStatus (/Users/sharath/webapps/docker/node_modules/express/lib/response.js:346:15)
at Command.callback (/Users/sharath/webapps/docker/test.js:24:13)
at normal_reply (/Users/sharath/webapps/docker/node_modules/redis/index.js:714:21)
at RedisClient.return_reply (/Users/sharath/webapps/docker/node_modules/redis/index.js:816:9)
at JavascriptRedisParser.returnReply (/Users/sharath/webapps/docker/node_modules/redis/index.js:188:18)
at JavascriptRedisParser.execute (/Users/sharath/webapps/docker/node_modules/redis-parser/lib/parser.js:415:12)
Http response statuses should be integers. It cannot be strings, objects, array or like that and should begin from 100.
From your code i see that you try to do
res.sendStatus(reply);
Check reply variable. From redis incr response im thinking it's string "OK".
Which is bad.. So to fix it just use
res.sendStatus(reply ? 200 : 500);
Also check this.
http://expressjs.com/en/4x/api.html#res.sendStatus
And this
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
EDIT
If you need to send some JSON or data into front-end just do like this
res.json({thisIsMyNumber: reply});
or
res.send({thisIsMyNumber: reply});
Hope this helps.

Node Server not working with SSL

I have a node server code on named server.js
var env = require('dotenv').config({path: '../.env'});
var fs = require("fs");
var options = {
key: fs.readFileSync(env.APP_SSL_PATH + 'server.key').toString(),
cert: fs.readFileSync(env.APP_SSL_PATH + 'server.crt').toString()
};
var app = require('express')();
var http = require('https');
var server = http.createServer(options, app);
var io = require('socket.io')(server);
var redis = require('redis');
// Check if server is listening on its port
server.listen(env.APP_NODE_PORT, function() {
console.log('Listening on your port');
io.on('connection', function (socket) {
console.log("new client connected");
var redisClient = redis.createClient();
redisClient.subscribe('notification-channel', function(err, count) {
});
redisClient.on("message", function(channel, message) {
console.log( " message= "+ message + " channel = " + channel);
socket.emit(channel, message);
});
socket.on('disconnect', function() {
redisClient.quit();
});
});
});
Using http it works fine but then when I add the SSL certificate on https the code is not working already and it doesn't throw any error. I run the node server.js by
node server.js > stdout.txt 2> stderr.txt
there are no error log showing on stderr.txt file. Please help me Im new on this. On the console
Listening on your port
will logged only it does not continue and log
new client connected
This is my client side code:
<script>
var socket = io.connect('{{ env("APP_URL") }}:8890');
socket.on('notification-channel', function (data) {
var header_count_elem = $('#menubar #header-messages-count');
var count = header_count_elem.text();
if (data != 'no-sound') {
$.get('/notification/notif-alerts', function(response) {
header_count_elem.text((response.count == '0') ? '' : response.count);
if (data != 'no-sound') {
if (count != response.count) {
var sound = '<audio id="audioplayer" autoplay=true volume=1>' +
'<source src="{{ url('assets/themes/cpanel/alarms/notification_sound.mp3') }}" type="audio/mpeg">' +
'<source src="{{ url('assets/themes/cpanel/alarms/notification_sound.ogg')}}" type="audio/ogg">' +
'</audio>';
$('body').append(sound);
}
}
});
}
});

nodejs + https + express - Error 324 (net::ERR_EMPTY_RESPONSE)

I have a nodejs server structured like so:
(app.js):
var fs = require('fs'),
http = require('http'),
https = require('https'),
express = require('express'),
connect = require('express/node_modules/connect'),
app = module.exports = express();
var ssl_options = {
key: fs.readFileSync('/etc/nginx/ssl/server.key'),
cert: fs.readFileSync('/etc/nginx/ssl/server.crt')
};
var server = https.createServer(ssl_options, app);
// EXPRESS
// app.set('view options', { layout: false });
var auth_token = "asdfasfdasdfasdf";
var express_session_id = "express.sid";
app.configure(function () {
app.use(express.cookieParser());
app.use(express.session({secret: auth_token, key: express_session_id}));
app.set("view options", {layout: false});
});
app.get('/', function (req, res) {
console.log (req.headers);
fs.readFile(__dirname + '/index.html', function(err, data){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data, 'utf8');
res.end();
});
});
app.listen = function(port) {
server.listen(port);
console_log.log('info', "COTTONMOUTH server listening on port " + port);
};
I have a cluster.js running the above app.js:
var cluster = require('cluster'),
os = require('os'),
workers = {};
if (cluster.isMaster) {
cluster.on('exit', function(worker, code, signal) {
if (worker.suicide === false) {
var exitCode = worker.process.exitCode;
console.error('worker ' + worker.process.pid + ' died ('+exitCode+'). restarting...');
cluster.fork();
}
});
var n = process.env.PROC || os.cpus().length;
for(var i = 0; i < n; i++ ) {
cluster.fork();
}
process.on('SIGTERM', function() {
console.log('[MASTER] Going for shutdown...');
for (var id in cluster.workers) {
console.log('\tkilling worker: ' + cluster.workers[id].process.pid);
cluster.workers[id].destroy();
}
console.log("[MASTER] Here's looking at you, kid.");
});
} else {
require('./app').listen(process.env.PORT || 3456);
}
My problem is that the following setup works fine on my localhost virtual box environment (ubuntu virtual running on a mac host). I am able to access the nodejs server with dev.domain.com:3456.
However, when I move this to my production rackspace server (same environment configs and setup), and try to access it by prod.domain.com:3456
The browser hangs for a bit and returns Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.
I did some research and have found some leads but weren't too helpful.
Any Ideas?
UPDATE:
when i lower the port down to 90, it seems to work which is interesting.
I am going to leave it at port 90 for now but if someone has an answer to why this is.
Thanks
I got this error message when my request grew too large (>65K). My solution was to reduce the data into several snippets.
Temporary Workaroud:
when i lower the port down to 90, it seems to work which is interesting. I am going to leave it at port 90 for now but if someone has an answer to why this is.
Thanks
This issue can also be encountered when you add an additional '/' from frontend to call a backend API
For example:
my route is
baseUrl/api/customer
but im sending request to
baseUrl/api/customer/
it will not work, at least this was in my case. Too dumb to notice this.
Maybe this can be helpful to someone

Resources