1, put the corresponding SSL certificate in the project file (I installed the image is Oneinstack, the creation of the project can be directly selected to generate the SSL certificate of the project, that is, Xxx.key and xxx.crt files);
2, modify the bin/www file, modify the code as follows:
#!/usr/bin/env node/** * Module dependencies. */var app = require ('.. /app '); var debug = require (' Debug ') (' https:server ');
Key packsvar path = require (' path '); var https = require (' https '); var fs = require (' FS ');
SSL certificate-related filesvar privatekey = Fs.readfilesync (Path.join (__dirname, './https.key '), ' utf8 '); var certificate = Fs.readfilesync ( Path.join (__dirname, './https.crt '), ' utf8 '); var credentials = {Key:privatekey, cert:certificate};/** * Get port from Environment and store in Express. */var port = normalizeport (Process.env.PORT | | ' 8081 ');Port number App.set (' Port ', port);/** * Create HTTP server. */var server = Https.createserver (credentials, app); The new HTTPS service/** * Listen on provided ports, on the all network interfaces. */server.listen (port); Server.on (' Error ', onError); Server.on (' Listening ', onlistening);/** * Normalize a port into a Number, string, or false. */function Normalizeport (val) {var port = parseint (val, 10); if (IsNaN (port)) {//named pipe return val; } if (port >= 0) {//port number return port; } return false;} /** * Event listener for HTTP Server "error" event. */function OnError (Error) {if (Error.syscall!== ' listen ') {throw error; } var bind = typeof Port = = = ' String '? ' Pipe ' + port: ' Port ' + port; Handle specific listen errors with friendly messages switch (error.code) {case ' eacces ': console.error (bind + ' requires elevated privileges '); Process.exit (1); Break Case ' Eaddrinuse ': console.error (bind + ' was already in use '); Process.exit (1); Break Default:throw error; }}/** * Event listener for HTTP server "listening" event. */function onlistening () {var addr = server.address (); var bind = typeof Addr = = = ' String '? ' Pipe ' + addr: ' Port ' + addr.port; Debug (' Listening on ' + Bind);}
3, the project restarts, input https://localhost:8081, can see the page as shown below, the HTTPS service is successful .
Note: Although it is already https service, but still will be reported unsafe prompt, is because of our certificate problem. Does not affect normal functionality.
CENTOS7 node Express project to upgrade HTTP interface to HTTPS interface workaround