windows express + https ssl 证书申请

 

第一步,下载并安装 openssl,并且将 bin 目录加入到环境变量

 
 

第二步,管理员运行cmd

mkdir cert && cd cert

# 生成私钥key文件
openssl genrsa -out server.key 1024

# 通过私钥文件生成CSR证书签名,一路回车即可
openssl req -new -key server.key -out server.pem

# 通过私钥文件和CSR证书签名生成证书文件
openssl x509 -req -days 365 -in server.pem -signkey server.key -out server.crt

 

第三步,启动 node express

var fs = require('fs')
var http = require('http')
var https = require('https')

var app = require('express')()
var privateKey = fs.readFileSync('./cert/server.key', 'utf8')
var certificate = fs.readFileSync('./cert/server.crt', 'utf8')
var credentials = { key: privateKey, cert: certificate }

var httpServer = http.createServer(app)
var httpsServer = https.createServer(credentials, app)
var PORT = 80
var SSLPORT = 443

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!')
    }
})

 

 

posted @ 2021-07-08 17:47  贝尔塔猫  阅读(111)  评论(0编辑  收藏  举报