一 openssl創建https私鑰和證書
1.下載windows版openssl:
http://slproweb.com/products/Win32OpenSSL.html
Win64OpenSSL_Light-1_1_1b.exe
2.安裝並使用openssl:
2.1 正常安裝openssl.exe
2.2 進入openssl安裝目錄的bin里面
#生成私鑰key文件
openssl genrsa 1024 > ./private.pem
#通過私鑰文件生成CSR證書簽名
openssl req -new -key ./private.pem -out csr.pem
#通過私鑰文件和CSR證書簽名生成證書文件
openssl x509 -req -days 365 -in csr.pem -signkey ./private.pem -out ./file.crt
二 windows下安裝和使用express框架:
1.全局安裝express框架,cmd打開命令行,輸入如下命令:
npm install -g express
express 4.x版本中將命令工具分出來,安裝一個命令工具,執行命令:
npm install -g express-generator
輸入express --version驗證
2.如果在執行js文件仍報Error: Cannot find module express錯誤。
解決辦法: 在自己的工程目錄下再次執行: npm install express
三 創建https服務器
1.進入node項目下,拷貝私鑰和證書到此目錄下
2.創建node服務程序https.js:
var app = require('express')(); var fs = require('fs'); var http = require('http'); var https = require('https'); var privateKey = fs.readFileSync('./private.pem', 'utf8'); var certificate = fs.readFileSync('./file.crt', 'utf8'); var credentials = {key: privateKey, cert: certificate}; var httpServer = http.createServer(app); var httpsServer = https.createServer(credentials, app); var PORT = 18080; var SSLPORT = 18081; httpServer.listen(PORT, function() { console.log('HTTP Server is running on: http://localhost:%s', PORT); }); httpsServer.listen(SSLPORT, function() { console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT); }); // Welcome app.get('/', function(req, res) { if(req.protocol === 'https') { res.status(200).send('Welcome to Safety Land!'); } else { res.status(200).send('Welcome!'); } });
3.運行:node https.js
4.瀏覽器訪問:https://localhost:18081/
參考:
https://blog.csdn.net/gengxiaoming7/article/details/78505107
https://www.cnblogs.com/handongyu/p/6260209.html
https://blog.csdn.net/mlsama/article/details/8021103