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

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.

Related

Getting "failed to start accepting connection" while deploying my app into bluemix

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.

testing local https server with mocha/superagent

So I see there was a pull request a few months ago for superagent to allow you to specify the CA in a request. It does not appear that the docs were updated to reflect this change, so I can't seem to figure out how to do it.
I am trying to test on my local machine a REST service which exposes both http and https endpoints. All the http ones work fine, the SSL ones....well.....not so much.
After spending all day yesterday running down certificate errors, I am 90% certain I have the server working correctly. Curl seems to think so, as does a vanilla node request object.
I assume superagent is probably creating a request under the hood - I just need to know how to pass in the CA for it.
Thanks in advance.
There is a usage example in their tests.
Basically:
var https = require('https'),
fs = require('fs'),
key = fs.readFileSync(__dirname + 'key.pem'),
cert = fs.readFileSync(__dirname + 'cert.pem'),
assert = require('better-assert'),
express = require('express'),
app = express();
app.get('/', function(req, res) {
res.send('Safe and secure!');
});
var server = https.createServer({
key: key,
cert: cert
}, app);
server.listen(8443);
describe('request', function() {
it('should give a good response', function(done) {
request
.get('https://localhost:8443/')
.ca(cert)
.end(function(res) {
assert(res.ok);
assert('Safe and secure!' === res.text);
done();
});
});
});
This worked for me:
...
var user = request.agent({ca: cert});
...
Full example:
var expect = require('chai').expect;
var should = require('should');
var request= require('superagent');
var fs = require('fs');
var cert = fs.readFileSync('sslcert/server.crt', 'utf8');
var validUser = { username: 'test#test.com', password: 'secret111' };
describe('User', function() {
// provide certificate as agent parameter
var user = request.agent({ca: cert});
it("/login", function(done) {
user
.get('https://localhost:3000/login')
.end(function(err, res) {
if(err) throw err;
// HTTP status should be 200
res.status.should.equal(200);
user
.post('https://localhost:3000/login')
.send(validUser)
.end(function(err, res) {
if(err) throw err;
// HTTP status should be 200
res.status.should.equal(200);
done();
// user will manage its own cookies
// res.redirects contains an Array of redirects
});
});
});
it("/", function(done) {
user
.get('https://localhost:3000/')
.end(function(err, res) {
if(err) throw err;
// HTTP status should be 200
res.status.should.equal(200);
done();
});
});
it("/logout", function(done) {
user
.get('https://localhost:3000/logout')
.end(function(err, res) {
if(err) throw err;
// HTTP status should be 200
res.status.should.equal(200);
done();
});
});
});

ENOENT error on "connect"

I'm trying to create an HTTP/S MitM forwarding proxy using Node.js.
The way I'm tackling this project is by reusing the solution found in ./lib/proxy.js file of the NPM Proxy Cache project created by #runk after he raised the issue on the Node HTTP Proxy project issue tracker.
My Proxy() class looks like this:
var request = require('request')
, https = require('https')
, http = require('http')
, net = require('net')
, url = require('url')
, os = require('os')
, fs = require('fs');
var SOCKET_PATH = os.tmpdir() + 'mitm.sock';
console.log('[SOCKET PATH] ' + SOCKET_PATH);
function Proxy (config) {
config = config || {};
if(fs.existsSync(SOCKET_PATH)) {
fs.unlinkSync(SOCKET_PATH);
}
var options = {
key: fs.readFileSync('./certs/dummy.key', 'utf8'),
cert: fs.readFileSync('./certs/dummy.crt', 'utf8')
};
// HTTPS Server
https.createServer(options, this.handler).listen(config.port + 1, this.hostname, function (e) {
if(e) {
console.log('[HTTPS] Server listen() error !');
throw e;
}
});
// HTTP Server
var server = http.createServer(this.handler);
server.listen(config.port, this.hostname, function (e) {
if(e) {
console.log('[HTTP] Server listen() error !');
throw e;
}
});
// Intercept CONNECT requests for HTTPS handshake
server.addListener('connect', this.httpsHandler);
}
Proxy.prototype.handler = function (req, res) {
var schema = !!req.client.pair ? 'https' : 'http'
, path = url.parse(req.url).path;
var dest = schema + '://' + req.headers['host'] + path;
console.log('(1) - [' + schema.toUpperCase() + '] ' + req.method + ' ' + req.url);
var params = {
rejectUnauthorized: false,
url: dest
};
if(req.method.toUpperCase() !== 'GET') {
return console.log('[HTTP] Request is not HTTP GET.');
}
var onResponse = function (e, response) {
if(e == null && response.statusCode === 200) {
return r.pipe(res);
}
var body = 'Status ' + response.statusCode + ' returned';
if(e) {
body = e.toString();
}
res.end(body);
};
var r = request(params);
r.on('response', onResponse.bind(null, null));
r.on('error', onResponse.bind(null));
};
Proxy.prototype.httpsHandler = function (request, socketRequest, bodyHead) {
var httpVersion = request['httpVersion']
, url = request['url'];
console.log('(2) - [HTTPS] ' + request['method'] + ' ' + request['url']);
var proxySocket = new net.Socket();
// ProxySocket event handlers
proxySocket.connect(SOCKET_PATH, function () {
proxySocket.write(bodyHead);
proxySocket.write('HTTP/' + httpVersion + ' 200 Connection established\r\n\r\n');
});
proxySocket.on('data', function (chunk) {
console.log('ProxySocket - "data"');
socketRequest.write(chunk);
});
proxySocket.on('end', function () {
console.log('ProxySocket - "end"');
socketRequest.end();
});
proxySocket.on('error', function (e) {
console.log('ProxySocket - "error"');
console.log(e);
console.log(e.stack);
socketRequest.write('HTTP/' + httpVersion + ' 500 Connection error\r\n\r\n');
socketRequest.end();
});
// SocketRequest event handlers
socketRequest.on('data', function (chunk) {
console.log('SocketRequest - "data"');
proxySocket.write(chunk);
});
socketRequest.on('end', function () {
console.log('SocketRequest - "end"');
proxySocket.end();
});
socketRequest.on('error', function (e) {
console.log('socketRequest - "error"');
console.log(e);
console.log(e.stack);
proxySocket.end();
});
};
module.exports = Proxy;
And my Index.js file that start my program looks like this:
var Proxy = require('./lib/proxy');
var proxy = new Proxy({
hostname: '127.0.0.1',
port: 8000
});
Here's my directory / file structure this:
/my_project
/certs
dummy.crt // Copied from the NPM Proxy Cache project
dummy.csr // Copied from the NPM Proxy Cache project
dummy.key // Copied from the NPM Proxy Cache project
/lib
proxy.js
index.js
I'm testing my program by setting (in Mac OSX Maverick) an HTTP and HTTPS proxy as IP address 127.0.0.1 and port 8000.
When browsing an HTTP only website everything works fine, but if I browse an HTTPS website I get the following error:
{[Error: connect ENOENT] code: 'ENOENT', errno: 'ENOENT', syscall: 'connect'}
Error: connect ENOENT
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
Any ideas from where this issue could come from and how to fix this ?
Thank you very much in advance !
(If you want to test my code, the NPM module request is the only dependency needed to run the code.)
EDIT: The certs can be downloaded from here : https://github.com/runk/npm-proxy-cache/tree/master/cert.
I'm an author of npm-proxy-cache. In fact I've created another project called thin https://www.npmjs.org/package/thin and I hope in future the npm proxy cache thing will utilize it. Despite the fact that it's still very rough it's usable and it does what you need.
E.g.
proxy code
var Thin = require('thin')
var proxy = new Thin;
// `req` and `res` params are `http.ClientRequest` and `http.ServerResponse` accordingly
// be sure to check http://nodejs.org/api/http.html for more details
proxy.use(function(req, res, next) {
console.log('Proxying:', req.url);
next();
});
// you can add different layers of "middleware" similar to "connect",
// but with few exclusions
proxy.use(function(req, res, next) {
if (req.url === '/foobar')
return res.end('intercepted');
next();
});
proxy.listen(8081, 'localhost', function(err) {
// .. error handling code ..
});
server code
var express = require('express'); // v3.4
var app = express();
app.use(express.urlencoded({limit: '10mb'}));
app.get('/test', function(req, res){
console.log(req.protocol, 'get req.query', req.query);
res.end('get: hello world');
});
app.post('/test', function(req, res) {
console.log(req.protocol, 'post req.query', req.query);
console.log(req.protocol, 'post req.body', req.body);
res.end('post: hello world');
});
app.listen(3000);
var fs = require('fs');
var https = require('https');
https.createServer({
key: fs.readFileSync('./cert/dummy.key'), // your mitm server keys
cert: fs.readFileSync('./cert/dummy.crt')
}, app).listen(3001);
You need to start proxy and server in two terminal sessions, then
curl -d "foo=baz" -k -x https://localhost:8081 https://localhost:3001/test?foo=bar
curl -d "foo=baz" -x http://localhost:8081 http://localhost:3000/test?foo=bar
After that you should be able to see following output from the server
https post req.query { foo: 'bar' }
https post req.body { foo: 'baz' }
http post req.query { foo: 'bar' }
http post req.body { foo: 'baz' }
Small example for interceptor
curl -d "foo=baz" -k -x https://localhost:8081 https://localhost:3001/foobar
It should return intercepted
Hope that helps :)

error in node.js TypeError: Object #<Object> has no method 'createserver' at Object.<anonymous> (/home/aashish/chatbox/main.js:5:16)

i am facing some error in developing chat server client on linux please help
var http = require('http');
fs =require('fs');
var app = http.createserver(function (request, response)
{
enter code herefs.readfile("client.html",utf-8,function(error,data)
{
response.writehead(200,{'content-type': 'text/html'});
response.write(data);
response.end();
})
}).listen(1337);
io.sockets.on('connection',function(socket)
{
socket.on('message_to_server',function(data)
{
io.socket.emit("message_to_client",{message: data["message"]});
});
});
// at Object. (/home/aashish/chatbox/main.js:5:16)
error
it's createServer where S is an uppercase letter
createServer() is now deprecated meanwhile you could use Server() instead .. just check the following snippet or simply use express web framework.
var http = require("http");
var server = http.Server(function(request, response) {
response.end("heeloo world");
});
server.listen(3030, function(err){
if(!err)
console.log("success");
else
console.log("error");
});

Try to get image from wikipedia and serve it in node.js

I am trying to make a webserver in node.js that downloads an image from Wikipedia and servers it on a page. I cant get it to work. I pasted my code in an online sandbox: http://runnable.com/UXWTyD3pTQ1RAADe.
Heres my code:
var http = require('http');
var fs = require('fs');
var fd = fs.open('name.jpeg', 'r+');
var options = {
host:'upload.wikimedia.org',
port:80,
path:'/wikipedia/commons/1/15/Jagdschloss_Granitz_4.jpg'
};
var server = http.createServer(function(req, res){
res.writeHead(200, ['Content-Type', 'text/html']);
http.get(options,function(res) {
res.on('data', function (chunk) {
fs.write(fd, chunk, 0, chunk.length, 0, null);
});
res.on('end',function(){
fd.end();
res.send("<img src='name.jpeg'></img>");
res.end();
});
});
});
server.listen(process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP);
I keep running into:
node server.js
Running...
fs.js:415
binding.write(fd, buffer, offset, length, position, wrapper);
^
TypeError: Bad argument
at Object.fs.write (fs.js:415:11)
at IncomingMessage.<anonymous> (server.js:18:12)
at IncomingMessage.EventEmitter.emit (events.js:96:17)
at IncomingMessage._emitData (http.js:359:10)
at HTTPParser.parserOnBody [as onBody] (http.js:123:21)
at Socket.socketOnData [as ondata] (http.js:1485:20)
at TCP.onread (net.js:404:27)
Working code - saving image file:
/**Try to get an image from Wikipedia and return it**/
var http = require('http');
var fs = require('fs');
var options = {
host:'upload.wikimedia.org',
port:80,
path:'/wikipedia/commons/1/15/Jagdschloss_Granitz_4.jpg'
};
var server = http.createServer(function(req, res){
res.writeHead(200, ['Content-Type', 'text/html']);
http.get(options,function(imgRes) {
imgRes.pipe(fs.createWriteStream('name.jpeg'));
res.end("<html><img src='name.jpeg'></img></html>");
});
});
server.listen(process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP);
You would also need node-static (http://www.sitepoint.com/serving-static-files-with-node-js/) for serving static file name.jpeg.
But the other way is to do it manually:
var http = require('http');
var fs = require('fs');
var options = {
host:'upload.wikimedia.org',
port:80,
path:'/wikipedia/commons/1/15/Jagdschloss_Granitz_4.jpg'
};
var server = http.createServer(function(req, res){
if(req.url == '/name.jpeg') {
res.writeHead(200, ['Content-Type', 'image/jpg']);
try {
var imgData = fs.readFileSync('name.jpeg');
res.end(fs.readFileSync('name.jpeg'));
} catch(err) {
res.end();
}
}
else {
res.writeHead(200, ['Content-Type', 'text/html']);
http.get(options,function(imgRes) {
imgRes.pipe(fs.createWriteStream('name.jpeg'));
res.end("<html><img src='name.jpeg'></img></html>");
});
}
});
server.listen(process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP);

Resources