Missing PFX or certificate + private key - node.js

I have set the keys to node.js but still i am unable to get it to working.
Can anybody tell me what should i do to make it work properly.
I need to work with https with node.js.
I get the following error.
`tls.js:1127
throw new Error('Missing PFX or certificate + private key.');
^
Error: Missing PFX or certificate + private key.
at Server (tls.js:1127:11)
at new Server (https.js:35:14)
at Object.exports.createServer (https.js:54:10)
at Object.<anonymous> (/var/www/html/fusionmate/nodejs/server.js:4:36)
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)`
Hers my code
var
app = require('https').createServer(handler),
io = require('socket.io')(app),
redis = require('redis'),
fs = require('fs'),
redisClient = redis.createClient();
var options = {
key: fs.readFileSync('/etc/apache2/ssl/apache.key'),
cert: fs.readFileSync('/etc/apache2/ssl/apache.crt')
};
app.createServer(options);
app.listen(3000);
console.log('Realtime Chat Server running at http://127.0.0.1:3000/');
function handler (req, res) {
fs.readFile(__dirname + '/index.html', function(err, data) {
if(err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}

There are two issues here:
options needs to be passed to https.createServer() as the first argument (with handler being the optional second argument), but you're just passing in a request handler function. For example:
var fs = require('fs');
var options = {
key: fs.readFileSync('/etc/apache2/ssl/apache.key'),
cert: fs.readFileSync('/etc/apache2/ssl/apache.crt')
};
var app = require('https').createServer(options, handler);
// ...
Further down, you're calling createServer() on an https.Server (app) instance, which isn't correct (you've already created a server instance and instances don't have such a method).

Related

Erro HTTPS node JS_

All my requests using my https tools, but ta giving file reading error. If I have already had the error and solved you can pass as resolved? I gave chmod -R 777 permission to the directory but it still keeps giving me an error.
Follow test:
app.js
var fs = require('fs');
var https = require('https');
//Local de arquivos ssl
var server_key = './home/admin/conf/web/ssl.chat';
var server_crt =./'home/admin/conf/web/ssl.chat.crt';
var server_pen ='./home/admin/conf/web/ssl.chat.pen';
var options = {
key: fs.readFileSync(server_key),
cert: fs.readFileSync(server_crt),
ca: fs.readFileSync(server_pen),
};
https.createServer(options, function (req, res) {
console.log(new Date()+' '+
req.connection.remoteAddress+' '+
req.method+' '+req.url);
res.writeHead(200);
res.end("hello world\n");
}).listen(4433);
--------------------Erro---------------------------------
$ node app.js
nternal/modules/cjs/loader.js:583
throw err;
^
Error: Cannot find module '/home/admin/web/chat/public_html/o'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
I was able to solve with a configuration on the routes. In my case, you have to create a separate route so that the socket can communicate correctly.
https://www.nginx.com/blog/nginx-nodejs-websockets-socketio/
https://www.linode.com/docs/uptime/loadbalancing/use-nginx-as-a-front-end-proxy-and-software-load-balancer/?fbclid=IwAR3qq-mhqI0AyivaHfL__eSkUgaWhOfvd4ujndBfA7JJFaRIPvyM3ZKnI0o

socket.io.users error from example

So I 100% copy pasted a code from the link below and I get the error below. I have installed all the dependencies required. I have used socket.io previously without problems, but never socket.io.users. The goal is to identify each PC as user.
var chatUsers = socketUsers.Users.of('/chat'); //
^
TypeError: Object #<Users> has no method 'of'
at Object.<anonymous> (/var/www/100moneta/components_not_larval/socket-user.js:16:35)
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
My code:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var socketUsers = require('socket.io.users');
socketUsers.Session(app);//IMPORTANT
var rootIo = require('socket.io')(server); //default '/' as namespace.
var chatIo = rootIo.of('/chat');
var rootUsers = socketUsers.Users; /* default '/' as namespace. Each namespace has IT's OWN users object list,
but the Id of a user of any other namespace may has the same value if request comes from the same client-machine-user.
This makes easy to keep a kind of synchronization between all users of all different namespaces. */
var chatUsers = socketUsers.Users.of('/chat'); //
rootIo.use(socketUsers.Middleware());//IMPORTANT but no errors if you want to skip it for a io.of(namespace) that you don't want the socket.io.users' support.
chatUsers.use(socketUsers.Middleware());
chatUsers.on('connected',function(user){
console.log(user.id + ' has connected to the CHAT');
user.set('username', 'username setted by server side'); /*at the store property you can store any type of properties
and objects you want to share between your user's sockets. */
user.socket.on('any event', function(data){ //user.socket is the current socket, to get all connected sockets from this user, use: user.sockets
});
chatIo.emit('set username',user.get('username')); //or user.store.username
});
rootUsers.on('connected',function(user){
console.log('User has connected with ID: '+ user.id);
});
rootUsers.on('connection',function(user){
console.log('Socket ID: '+user.socket.id+' is user with ID: '+user.id);
});
rootUsers.on('disconnected',function(user){
console.log('User with ID: '+user.id+'is gone away :(');
});
//You can still use the io.on events, but the execution is after connected and connection of the 'users' and 'chatUsers', no matter the order.
rootIo.on('connection',function(socket){
console.log('IO DEBUG: Socket '+ socket.id+ ' is ready \n');
});
Link with the code and tutorial: https://www.npmjs.com/package/socket.io.users

Parse server migration to IBM bluemix

I am trying to run parse server with nodejs in ibm bluemix but it is throwing an error in parse server PromiseRouter file.
PromiseRouter.js:48
throw _iteratorError;
^
ReferenceError: Symbol is not defined
How can i get this resolved
My App .js
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var app = express();
var port = process.env.PORT || 1337;
// Specify the connection string for your mongodb database
// and the location to your Parse cloud code
var api = new ParseServer({
databaseURI: 'mongodb://IBM_MONGO_DB',
cloud: './cloud/main.js', // Provide an absolute path
appId: 'MYAPPID',
masterKey: 'MYMASTER_KEY', //Add your master key here. Keep it secret!
serverURL: 'http://localhost:' + port + '/parse' // Don't forget to change to https if needed
});
app.use('/parse', api);
app.get('/', function(req, res) {
res.status(200).send('Express is running here.');
});
app.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
Response :
/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/node_modules/parse-server/lib/PromiseRouter.js:48
throw _iteratorError;
^
ReferenceError: Symbol is not defined
at PromiseRouter.merge (/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/node_modules/parse-server/lib/PromiseRouter.js:33:40)
at new ParseServer (/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/node_modules/parse-server/lib/index.js:137:10)
at Object.<anonymous> (/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/app.js:10:11)
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:906:3
This is the function in PromiseRouter.js that is throwing an error
PromiseRouter.prototype.merge = function (router) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = router.routes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var route = _step.value;
this.routes.push(route);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
};
This is all i have
The reason why Symbol is not found is because it is an ES6 feature that is not supported in your current Node.js build. Check to make sure your Node.js runtime is at least v4 (see compatibility here).
The easy way to ensure your Node.js build on Bluemix is running at least v4.0 is to define your engine variable in your app's package.json file as such:
{ "engines" : { "node" : ">=4.0" } }
After updating your package.json file, re-push your application to Bluemix and it will build it with your defined version of Node.js

Socket.io and module.exports are not working together. How do I fix this?

I am learning Node.js. I just found about module.exports. It seems to me that this is a way to help keep code clean and maintainable by separating code.
I tried out a few examples and it works. I got to console.log a few things by calling the method and it ran the function that was on another file.
I also learned some socket.io. I have got it to work as well.
I wanted to separate the code so I put all the socket.io connection information in a separate file and called the method on the main server file.
It doesn't work. The only way everything works if all the code is on the same page.
This is what I have:
app.js
var app = require('express')();
var ioConnect = require('./ioConnect.js')
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
ioConnect.ioConnection();
ioConnect.js
function addScore() {
var io = require('socket.io');
io.on('connection', function(socket) {
socket.on('score', function(data) {
socket.emit('addScore', 15);
});
});
}
module.exports.ioConnection = addScore;
At first I got an error that said: "io is not defined" so I added
var io = require('socket.io)(server); and got server is not defined so I tried
var io = require('socket.io'); and got this error:
/root/game/ioConnect2.js:5
io.on('connection', function(socket) {
^
TypeError: Object function Server(srv, opts){
if (!(this instanceof Server)) return new Server(srv, opts);
if ('object' == typeof srv && !srv.listen) {
opts = srv;
srv = null;
}
opts = opts || {};
this.nsps = {};
this.path(opts.path || '/socket.io');
this.serveClient(false !== opts.serveClient);
this.adapter(opts.adapter || Adapter);
this.origins(opts.origins || '*:*');
this.sockets = this.of('/');
if (srv) this.attach(srv, opts);
} has no method 'on'
at Object.addScore [as ioConnection] (/root/game/ioConnect2.js:5:16)
at Object.<anonymous> (/root/game/app:8:19)
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:906:3
If I put the code together on one file everything works. Can someone please explain to me exactly whats going on here and what I need to do?
When you require socket.io it returns a function. In app.js you called that require/function with an argument and stored the return value in 'io'. Good so far. In ioConnect.js you are storing the function itself in io. rather than do that, you should pass the io you set in app.js to the function returned by your require of ioConnect.js.
app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var ioConnect = require('./ioConnect.js')(io);
server.listen(80);
ioConnect.addScore();
ioConnect.js
function ioConnection(io) {
if (!(this instanceof ioConnection)) {
return new ioConnection(io);
}
this.io = io;
}
ioConnection.prototype.addScore = function() {
this.io.on('connection', function (socket) {
socket.on('score', function (data) {
socket.emit('addScore', 15);
});
});
}
module.exports = ioConnection;

How do I serve a page over https using expressjs?

I'm new to nodejs/expressjs. Could someone please explain how to to serve a page over https?
I have to ask this question another way, stackoverflow is complaining that my post is mainly code?
Here is the error dump:
app.get('/', function(request, response) {
^
TypeError: Object # has no method 'get' at Object.
(/home/john/startup/docm/w2.js:21:5) 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:901:3
And here is the code:
var express = require('express');
var fs = require('fs');
var app = express();
var options = {
ca: fs.readFileSync('csr.pem'),
cert: fs.readFileSync('cert.pem'),
key: fs.readFileSync('key.pem')
};
var server = require('https').createServer(options);
var portNo = 8889;
var app = server.listen(portNo, function() {
console.log((new Date()) + " Server is listening on port " + 8888);
});
app.get('/', function(request, response) {
app.use(express.static(__dirname));
console.log('app.get slash');
var buf = new Buffer(fs.readFileSync('index1.html'), 'utf-8');
response.send(buf.toString('utf-8'));
});
I'm new to nodejs/expressjs. Could someone please explain how to to serve a page over https?
The problem with your application is that you're overriding your Express instance with your HTTPS instance. This is how it is properly done:
var fs = require('fs');
var express = require('express');
var app = express();
var https = require('https');
var options = {
ca: fs.readFileSync('csr.pem'),
cert: fs.readFileSync('cert.pem'),
key: fs.readFileSync('key.pem')
};
var server = https.createServer(options, app);
server.listen(443, function() {
console.log((new Date()) + ' Server is listening on port 443');
});
app.use(express.static(__dirname));
app.get('/', function(req, res) {
console.log('app.get slash');
var file = fs.readFileSync('index1.html', {encoding: 'utf8'});
res.send(file);
});
These were the errors in your code:
Instead of passing Express to HTTPS you overwrote Express with the HTTPS instance.
You did not pass your Express application to your HTTPS instance.
The Express static() middleware should be served outside of specific request handlers.
You passed a buffer to another buffer to set its encoding although readFileSync() already has an encoding option.

Resources