express js https code example
Example 1: express js server
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('<h1>Some HTML</h1>');
res.send('<p>Even more HTML</p>');
});
app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));
Example 2: https with express
const fs = require('fs');
const https = require('https');
const app = require('express')();
app.get('*', (req, res) => res.send('<h1>Hello, World</h1>'));
const server = https.createServer({
key: fs.readFileSync(`${__dirname}/localhost-key.pem`, 'utf8'),
cert: fs.readFileSync(`${__dirname}/localhost.pem`, 'utf8')
}, app);
await server.listen(443);
Example 3: express http to https
var express = require('express');var app = express(); var redirectToHTTPS = require('express-http-to-https').redirectToHTTPS // Don't redirect if the hostname is `localhost:port` or the route is `/insecure`app.use(redirectToHTTPS([/localhost:(\d{4})/], [/\/insecure/], 301)); app.get('/', function (req, res) { res.send('Hello World!');}); app.get('/insecure', function (req, res) { res.send('Dangerous!');}); app.listen(3000, function () { console.log('Example app listening on port 3000!');}); app.listen(8080, function () { console.log('Example app listening on port 8080 insecurely!');});