Node.js and Express serving the same content for HTTP and HTTPS via SSL
In my previous post I explained how to set up SSL for Node.js/Express. Now, I want to serve the same content using the same logic for both http and https, and I don’t want to duplicate my code.
The idea is to move everything involving Express app. into a function. Call the function for both http and https server. If you have global variables, make sure they are outside of this function:
var apps = express.createServer({key: pkey, cert: cert, ca: [dad1,dad2]}); var app = express.createServer(); apps.listen(443); app.listen(80); startServer(app, false); startServer(apps, true); function startServer(app, isSSL) { app.configure(function () { // just some sample code app.use(express.cookieParser()); app.use(express.bodyParser()); app.use(connect.static(‘public’)); }); app.get(‘/’, function(req, res){ if (isSSL) res.end(‘Hello HTTPS’); else res.end(‘Hello HTTP’); }); }
This works, although I hope there is some nicer solution.
Tweet to @mbabuskov Tweet Milan Babuškov, 2011-12-01