Skip to content

Commit 633e1bd

Browse files
committed
Express with SSL example
1 parent 06d1175 commit 633e1bd

File tree

4 files changed

+61
-0
lines changed

4 files changed

+61
-0
lines changed

examples/ssl/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
**/*.pem

examples/ssl/Readme.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Express server with SSL enabled
2+
3+
Please create the self-signed certificate and private key to path `/certs` by following command:
4+
5+
```bash
6+
./create_certs.sh
7+
```
8+
9+
When running this example, the application runs on
10+
11+
* https://localhost:8443
12+
13+
and asks the user to make a security exception in the browser in order to see the pages.
14+
CAUTION: *Self-signed certificates should never be used in production environments!*

examples/ssl/create_certs.sh

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#!/bin/bash
2+
3+
mkdir -p certs && \
4+
cd certs && \
5+
openssl req -x509 -newkey rsa:4096 -nodes -sha256 -subj '/CN=localhost' -days 3650 -keyout key.pem -out cert.pem

examples/ssl/index.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Module dependencies.
3+
*/
4+
5+
var express = require('../..');
6+
var fs = require('fs');
7+
var path = require('path');
8+
var https = require('https');
9+
10+
var app = module.exports = express();
11+
12+
app.use(function(req, res) {
13+
res
14+
.set('Content-Type', 'text/html;charset=utf-8')
15+
.status(200)
16+
.send('<h1>Hello world from a SSL-enabled server!</h1>')
17+
.end();
18+
});
19+
20+
/* istanbul ignore next */
21+
if (!module.parent) {
22+
try {
23+
/* These certificates should be created manually as specified in the
24+
* Readme.md */
25+
var certsPath = path.join(__dirname, 'certs');
26+
var options = {
27+
key: fs.readFileSync(path.join(certsPath, 'key.pem')),
28+
cert: fs.readFileSync(path.join(certsPath, 'cert.pem'))
29+
};
30+
31+
/* Instead of using app.listen() directly, you should create a regular
32+
* Node.js HTTPS server and place the Express server as its only midware. */
33+
var httpsServer = https.createServer(options, app);
34+
var PORT = 8443;
35+
httpsServer.listen(PORT, function() {
36+
console.log('SSL Express server responds in https://localhost:' + PORT);
37+
});
38+
} catch(er) {
39+
console.error('Please create the certificates manually first according to the Readme.md.');
40+
}
41+
}

0 commit comments

Comments
 (0)