How to use routes from Express to HTTPS?

I allow https requests to my nodeJS server. But I would like to use the same routes that I can get from http requests with this port 8080 to my https with this 443 port.

http://api.myapp.com:8080/api/waitlist/join successfully https://api.myapp.com:443/api/waitlist/join not What I miss in the code to use the same routes as for the "app" for httpsServer?

var fs = require('fs'); var https = require('https'); var express = require('express'); // call express var app = express(); // define our app using express var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var cors = require('cors'); var config = require('./config'); // Configure app to use bodyParser() [...] // Configure the CORS rights app.use(cors()); // Enable https var privateKey = fs.readFileSync('key.pem', 'utf8'); var certificate = fs.readFileSync('cert.pem', 'utf8'); var credentials = { key: privateKey, cert: certificate }; var httpsServer = https.createServer(credentials, app); // Configure app port var port = process.env.PORT || config.app.port; // 8080 // Configure database connection [...] // ROUTES FOR OUR API // ============================================================================= // Create our router var router = express.Router(); // Middleware to use for all requests router.use(function(req, res, next) { // do logging console.log('>>>> Something is happening. Here is the path: '+req.path); next(); }); // WAITLIST ROUTES --------------------------------------- // (POST) Create Email Account --> Join the waitList router.route('/waitlist/join').post(waitlistCtrl.joinWaitlist); // And a lot of routes... // REGISTER OUR ROUTES ------------------------------- // All of our routes will be prefixed with /api app.use('/api', router); // START THE SERVER // ============================================================================= app.listen(port); httpsServer.listen(443); 

Thanks!

+5
source share
2 answers

Using the docs API for .listen in my own projects with a similar need and looking at your code, I think that two quick changes should work:

1) add var http = require('http'); to the top, demanding from your other.

2) change the last two lines of the application to:

 // START THE SERVER // ============================================================================= http.createServer(app).listen(port); https.createServer(credentials, app).listen(443); 

(If this works, you can also remove the link to httpsServer .)

+7
source

Sincerely, if you have no good reason for me not to look at the web server (NGINX) in front of your node application or load balancer.

This helps in several ways, not least because you can complete the HTTPS request there, and let your node application not care.

+3
source

All Articles