我的環境
生成證書
輸入如下命令會在你的當前文件夾生成localhost.key和localhost.cert.
openssl genrsa -out localhost.key 2048 openssl req -new -x509 -key localhost.key -out localhost.cert -days 3650 -subj /CN=localhost
其中localhost為域名. 想要換成別的域名就直接把上面的所有localhost替換成你的域名.
以我為例, 我的虛擬機的域名是xxx.compute.amazonaws.com
, 就以這個域名替換上面所有的localhost, 會生成, ec2-34-220-96-9.us-west-2.compute.amazonaws.com.key
和 ec2-34-220-96-9.us-west-2.compute.amazonaws.com.cert
兩個文件.
更新
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365
如果不想用密碼保護私鑰, 加上-nodes.
加上-subj '/CN=localhost'
可以設置certificate的內容. 將其中的localhost
替換成你的域名.
參考:How to create a self-signed certificate with openssl?
代碼
想要運行如下代碼, 需要先安裝包
npm init npm i -S https express
創建文件index.js, 內容如下.
#!/usr/bin/env node var https = require('https'); var fs = require('fs'); var express = require('express'); var host = 'xxx.compute.amazonaws.com'; // Input you domain name here. var options = { key: fs.readFileSync( './' + host + '.key' ), cert: fs.readFileSync( './' + host + '.cert' ), requestCert: false, rejectUnauthorized: false }; var httpApp = express(); var app = express(); app.get('/', function (req, res) { res.send('hi HTTPS'); }); httpApp.get('/', function (req, res) { res.send('hi HTTP'); }); httpApp.listen(80, function () { console.log('http on 80'); }); var server = https.createServer( options, app ); server.listen( 443, function () { console.log( 'https on 443' ); } );
啟動服務器
sudo node index.js
訪問
瀏覽器中輸入http://xxx.compute.amazonaws.com/
就會以80端口訪問HTTP服務器. 顯示hi HTTP
.
輸入https://xxx.compute.amazonaws.com/
就會以443端口訪問HTTPS服務器, 顯示hi HTTPS
.
參考
Self-Signed, Trusted Certificates for Node.js & Express.js
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com