How do I serve a page over https using expressjs? - node.js

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.

Related

connectivity to mongodb issue

I have the following code in a script.js file:
var express = require('express'),
app = express(),
cons = require('consolidate'),
MongoCl = require('mongodb').MongoClient,
Server = require('mongodb').Server;
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname +'/views');
var mongoclient = new MongoCl( new Server('localhost', 27017, {'native_parser' : true}));
var db = mongoclient.db('course');
app.get('/', function (req,res) {
db.collection('hello_mongo_express').findOne({}, function (err, doc) {
res.render('hello',doc);
});
});
app.get('*', function (req,res) {
res.send('Page not found',404);
});
mongoclient.open(function (err, mongoclient) {
if(err) throw err;
var port = 8080;
app.listen(port);
console.log("Express server started on port "+port);
});
./views/hello.html looks like :
<h1>Hello, {{name}}</h1>
I have a valid collection within a db 'course'.
When I try running using node, I face the following issue:
F:\mongo_proj>node script.js
F:\mongo_proj\script.js:11
var db = mongoclient.db('course');
^
TypeError: mongoclient.db is not a function
at Object.<anonymous> (F:\mongo_proj\script.js:11:22)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
Even though, I guess all the code that creates the mongoclient, db objects, will get called only when the db connectivity is been established. So what could the issue be
edit:
I tried #jerry's suggestion:
try this.. this simple way of connection
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
db.close();
});
refer this link and try this
https://www.npmjs.com/package/mongodb
This issue is coming because, you are trying to use mongoclient before it opens connection. So wrap the code in open function as follow:
var db;
mongoclient.open(function (err, mongoclient) {
db = mongoclient.db('course');
if(err) throw err;
var port = 8080;
app.listen(port);
console.log("Express server started on port "+port);
});
See the link for further reference mongo connection
Also this .open() method is used in older versions. With newer version use .connect() method instead. For later versions may be refer this node driver manual

Missing PFX or certificate + private key

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

error on creating new object from serialport node.js

I've check such kind of issue. but i don't find any. if you found it. just let me know.
I just getting started write javascript through node.js, and serialport. cand someone explain me why this error appear?
/Applications/MAMP/htdocs/homeautomation/server.js:42
var sp = new serialPort(portName, {
^
TypeError: undefined is not a function
at Object.<anonymous> (/Applications/MAMP/htdocs/homeautomation/server.js:42:10)
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
this is my starting code
/*
* dependencies
*/
var express = require('express'),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
serialPort = require('serialport').serialPort;
server.listen(3000);
console.log('listen on port 3000')
/*
* Express
*/
var app = express();
// serve static files from index
app.configure(function(){
app.use(express.static(__dirname + '/'));
});
// respon to web GET request on index.html
app.get('/', function (req, res){
res.sendfile(__dirname + '/index.html');
});
/*
* Serial Port Setup
*/
var portName = '/dev/tty.usb.serial-A501JUTF';
//var portName = '/dev/tty.usbmodem1421';
var readData = ''; //Array to hold the values read from the port
var sp = new serialPort(portName, {
baudRate : 9600,
dataBits : 8,
parity : 'none',
stopBits: 1,
flowControl : false,
});
any help will be appreciated.
Your code is correct, except that you used the serialPort object of the require('serialport') library, when it's in fact SerialPort that you need to use, hence the undefined is not a function error that you encountered.
var SerialPort = require("serialport")
console.log(SerialPort.serialPort); // undefined
console.log(SerialPort.SerialPort); // { [Function: SerialPort, ... }
See the documentation for a sample usage.
Try this. It works perfectly.
var SerialPort = require('serialport');
var serialPort = SerialPort.serialPort;
var sp = new SerialPort("/dev/ttyACM0", {
});

GET http://localhost:3000/socket.io/socket.io.js 404 (Not Found)

I'm trying to stream data to the browser. I'm struggling, however, to connect it to the browser. Here's my html:
<ul class="tweets"></ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
jQuery(function ($) {
var tweetList = $('ul.tweets');
socket.on('tweet', function (data) {
tweetList .prepend('<li>' + data.user + ': ' + data.text + '</li>');
});
});
</script>
And here's the relevant parts of my app.js:
var express = require('express')
, twitter = require('ntwitter')
, http = require('http')
, path = require('path');
var app = express();
var io = require('socket.io').listen(app);
app.get('/', function (req, res) { res.sendfile(__dirname + '/index.html'); });
app.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
io.sockets.volatile.emit('tweets', {
user: data.user.screen_name,
text: data.text,
geo : geo,
latitude: latitude,
longitude: longitude
});
I installed socket.io 0.9.16 via my packages.json file:
"dependencies": {
"express": "3.2.6",
"jade": "*",
"ntwitter":"0.2.10",
"socket.io":"0.9.x"
}
Can anyone help me out here? Why can't it find the file?
Digging a bit deeper. To test the socket, I put this in the app.js:
var socket = io.listen(app);
And I get the error:
TypeError: Object #<Manager> has no method 'listen'
at Object.<anonymous> (/home/andy/dev/node/mytwittermap/app.js:49:17)
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
Your setup needs to look something like this:
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
...
server.listen(app.get('port')); // not 'app.listen'!
Can you try this:
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
I guess, you will have to instantiate the socket.io server.
You need to instantiate the socket.io connection and
You need to use server.listen() and not app.listen()
Try something like this:
// at the top of app.js
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
// your code
// at the bottom of app.js
server.listen('3000', () => {
console.log('Server listening on Port 3000');
})

Express module error while listening http server in nodejs

I have created a nodejs http server
var http = require("http");
var url = require("url");
var express = require('express');
var app = express();
function start(route, handle){
function onRequest(request,response){
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response, request);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started");
app.listen(8888);
console.log('Express app listening on port 8888');
}
it gives error
f:\Labs\nodejs\webapp>node index.js
Server has started
Express app listening on port 8888
events.js:66
throw arguments[1]; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:769:11)
at Server._listen2 (net.js:909:14)
at listen (net.js:936:10)
at Server.listen (net.js:985:5)
at Function.app.listen (f:\Labs\nodejs\webapp\node_modules\express\lib\appli
cation.js:532:24)
at Object.start (f:\Labs\nodejs\webapp\server.js:15:6)
at Object.<anonymous> (f:\Labs\nodejs\webapp\index.js:11:8)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
when i change the port of app.listen it dont throw this error, what can be done?
will changing port other than server port will keep the session of the server on another port??
and how can i access this app variable in other js page to get/set the data?
If you intend to run on the same port, you can see if you have currently running node processes with
ps aux | grep node
and then kill -9 PROCESSID
You can't have multiple things listening on the same port like this, hence the EADDRINUSE error. If you want to create your own http server while using Express, you can do it like this:
var express = require('express');
var https = require('https');
var http = require('http');
var app = express();
http.createServer(app).listen(8888);
https.createServer(options, app).listen(443);
From the Express docs:
The app returned by express() is in fact a JavaScript Function,
designed to be passed to node's http servers as a callback to handle
requests.
Or you can just do
app.listen(8888);
And then Express will setup an http server for you.
You would then set up your routes in Express to actually handle requests coming in. With Express, routes look like this:
app.get('/foo/:fooId', function(req, res, next) {
// get foo and then render a template
res.render('foo.html', foo);
});
If you want to access your app in other modules (usually for testing) you can just export it like any other variable:
module.exports.app = app;
You'll then be able to require('./app').app in other modules.

Resources