个人博客地址,更多精彩内容
- 首先你需要生成https证书,免费的https证书可能会是key或者crt或者pem结尾的。不同格式之间可以通过OpenSSL转换
openssl x509 -in mycert.crt -out mycert.pem -outform PEM
Node原生版本
const https = require('https')
const path = require('path')
const fs = require('fs')
const privateKey = fs.readFileSync(path.join(__dirname, './certificate/private.key'), 'utf8')
const certificate = fs.readFileSync(path.join(__dirname, './certificate/certificate.crt'), 'utf8')
const credentials = {
key: privateKey,
cert: certificate,
}
const httpsServer = https.createServer(credentials, async (req, res) => {
res.writeHead(200)
res.end('Hello World!')
})
const SSLPORT = 443
httpsServer.listen(SSLPORT, () => {
console.log(`HTTPS Server is running on: https://localhost:${SSLPORT}`)
})
express版本
const express = require('express')
const path = require('path')
const fs = require('fs')
const https = require('https')
const privateKey = fs.readFileSync(path.join(__dirname, './certificate/private.key'), 'utf8')
const certificate = fs.readFileSync(path.join(__dirname, './certificate/certificate.crt'), 'utf8')
const credentials = {
key: privateKey,
cert: certificate,
}
const app = express()
app.get('/', async (req, res) => {
res.status(200).send('Hello World!')
})
const httpsServer = https.createServer(credentials, app)
const SSLPORT = 443
httpsServer.listen(SSLPORT, () => {
console.log(`HTTPS Server is running on: https://localhost:${SSLPORT}`)
})
koa版本
const koa = require('koa')
const path = require('path')
const fs = require('fs')
const https = require('https')
const privateKey = fs.readFileSync(path.join(__dirname, './certificate/private.key'), 'utf8')
const certificate = fs.readFileSync(path.join(__dirname, './certificate/certificate.crt'), 'utf8')
const credentials = {
key: privateKey,
cert: certificate,
}
const app = koa()
app.use(async ctx => {
ctx.body = 'Hello World!'
})
const httpsServer = https.createServer(credentials, app.callback())
const SSLPORT = 443
httpsServer.listen(SSLPORT, () => {
console.log(`HTTPS Server is running on: https://localhost:${SSLPORT}`)
})
个人博客地址,更多精彩内容