使用 git客户端msysgit , 其中已包含了 openssl 程序
# 生成私钥 key 文件
openssl genrsa -out privatekey.pem 1024
# 通过私钥生成CSR证书签名
openssl req -new -key privatekey.pem -out certrequest.csr
# 通过私钥和证书签名生成证书文件
openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem
有了证书之后,开始创建服务
const https = require("https"); const http = require("http"); const fs = require("fs") // 创建 http 服务 const httpServer = http.createServer((req, res) => { res.writeHead(200); res.end("this is a http server") }) httpServer.listen(3000, function() { console.log("http server is running on: http://localhost:3000"); }) // 创建 https 服务 const privateKey = fs.readFileSync('./privateKey.pem') const certificate = fs.readFileSync('./certificate.pem') const httpsServer = https.createServer({ key: privateKey, cert: certificate }, (req, res) => { res.writeHead(200); res.end("this is a https server") }) httpsServer.listen(3006, function() { console.log("https server is running on https://localhost:3006") })
完成,打开浏览器访问 localhost:3000, https://localhost:3006 即可。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/289733.html