+86 135 410 16684Mon. - Fri. 10:00-22:00

Node.js – Express 4.x 使用 HTTPS/SSL

Node.js - Express 4.x 使用 HTTPS/SSL

Node.js – Express 4.x 使用 HTTPS/SSL

產生 express app

先安裝 express generator

$ npm install -g express-generator

使用 generator 產生基本的 app,這邊 app 名稱取為 myapp

$ express --css stylus myapp

安裝相依套件並測試執行

$ cd myapp
$ npm install

//執行
$ npm start

查看 http://localhost:3000,是否有啟動成功

expres_npm_start

產生 SSL 憑證

$ openssl genrsa -out yourkey.pem 1024
$ openssl req -new -key  yourkey.pem -out  yourcsr.csr
$ openssl x509 -req -in yourcsr.csr -signkey yourkey.pem -out yourcert.pem

若已有,也須確保格式皆需轉成 .pem

$ openssl x509 -in yourkey.crt -out yourkey.pem -outform PEM
$ openssl x509 -in yourcert.crt -out yourcert.pem -outform PEM

myapp 底下創建一個 ssl 資料夾,並將創建的憑證檔案全放入其中

修改 app 程式碼

目前 myapp 的資料結構如下:

$ tree myapp
myapp/
├── app.js
├── bin
│   └── www
├── node_modules
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       ├── style.css
│       └── style.styl
├── routes
│   ├── index.js
│   └── users.js
├── ssl
│   ├── yourcert.pem
│   ├── yourcsr.csr
│   └── yourkey.pem
└── views
    ├── error.jade
    ├── index.jade
    └── layout.jade

myapp 底下新建一個 sslLicense.js 的檔案,內容如下:

sslLicense.js
var fs = require('fs');

//ssl license

var keyPath = 'ssl/yourkey.pem';
var certPath = 'ssl/yourcert.pem';

var hskey = fs.readFileSync(keyPath);
var hscert = fs.readFileSync(certPath);

var options = {
    key: hskey,
    cert: hscert
};

//ssl object

var ssl = {};

ssl.options = options;

module.exports = ssl;

原本的 bin/www 內容

bin/www
#!/usr/bin/env node
var debug = require('debug')('myapp');
var app = require('../app');

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
});

要開啟 https 不能直接使用 express 的 listen,要改用 node.js 本身的 https 的 api。因此 bin/www 修改成以下內容:

bin/www
#!/usr/bin/env node
var debug = require('debug')('myapp');
var app = require('../app');
var ssl = require('../sslLicense');

var http = require('http'),
    https = require('https');


app.set('port', process.env.PORT || 3000);
app.set('httpsport', 8080);


var httpServer = http.createServer(app).listen(app.get('port'));
var httpsServer = https.createServer(ssl.options, app).listen(app.get('httpsport'));

再次執行 npm start,並分別查看 http://localhost:3000https://localhost:8080

express_https

看到上圖表示啟動成功