最近遇到开发需求,需要在本地同时起http服务和https服务,在此做一下简单记录,方便之后查询
一、https需要申请SSL证书,经过了解,获取SSL证书的方式有3种,暂不做详细介绍
- 使用openssl免费生成证书
- 阿里云可以申请免费的SSL证书
- 可以在很多官方的平台上购买SSL证书
二、在此主要记录一下nodejs配置https的方式
首先需要把证书放在项目里面
- node原生版
import https from 'https'
import path from 'path'
impot fs from 'fs'
const option = {
key : fs.readFileSync(path.join(`${__dirname}/certs/test.key`)),
cert : fs.readFileSync(path.join(`${__dirname}/certs/test.pem`))
}
https.createServer(option, async(req,res)=>{
res.writeHead(200)
res.end('启动https服务')
}).listen(443, err => {
console.log('运行在https端口:443')
})
- express
import express from 'express'
import https from 'https'
import path from 'path'
impot fs from 'fs'
const app = express()
const option = {
key : fs.readFileSync(path.join(`${__dirname}/certs/test.key`)),
cert : fs.readFileSync(path.join(`${__dirname}/certs/test.pem`))
}
https.createServer(option, app).listen(443, err => {
console.log('运行在https端口:443')
})
- koa
import koa from 'koa'
import https from 'https'
import path from 'path'
impot fs from 'fs'
const app = new koa()
const option = {
key : fs.readFileSync(path.join(`${__dirname}/certs/test.key`)),
cert : fs.readFileSync(path.join(`${__dirname}/certs/test.pem`))
}
https.createServer(option, app.callback()).listen(443, err => {
console.log('运行在https端口:443')
})