nodejs启用https

404 阅读1分钟

最近遇到开发需求,需要在本地同时起http服务和https服务,在此做一下简单记录,方便之后查询

一、https需要申请SSL证书,经过了解,获取SSL证书的方式有3种,暂不做详细介绍
  1. 使用openssl免费生成证书
  2. 阿里云可以申请免费的SSL证书
  3. 可以在很多官方的平台上购买SSL证书
二、在此主要记录一下nodejs配置https的方式
首先需要把证书放在项目里面
  1. node原生版
import https from 'https'
import path from 'path'
impot fs from 'fs'

// 读取SSL证书内容
const option = {
  key  : fs.readFileSync(path.join(`${__dirname}/certs/test.key`)),
  cert : fs.readFileSync(path.join(`${__dirname}/certs/test.pem`))
}

// 创建https服务器实例,并且启动服务器监听端口
https.createServer(option, async(req,res)=>{
  res.writeHead(200)
  res.end('启动https服务')
}).listen(443, err => {
    console.log('运行在https端口:443')
})
  1. express
import express from 'express'
import https from 'https'
import path from 'path'
impot fs from 'fs'

// 创建express实例
const app = express()

// 读取SSL证书内容
const option = {
  key  : fs.readFileSync(path.join(`${__dirname}/certs/test.key`)),
  cert : fs.readFileSync(path.join(`${__dirname}/certs/test.pem`))
}

// 创建https服务器实例,并且启动服务器监听端口
https.createServer(option, app).listen(443, err => {
    console.log('运行在https端口:443')
})
  1. koa
import koa from 'koa'
import https from 'https'
import path from 'path'
impot fs from 'fs'

// 创建koa实例
const app = new koa()

// 读取SSL证书内容
const option = {
  key  : fs.readFileSync(path.join(`${__dirname}/certs/test.key`)),
  cert : fs.readFileSync(path.join(`${__dirname}/certs/test.pem`))
}

// 创建https服务器实例,并且启动服务器监听端口
https.createServer(option, app.callback()).listen(443, err => {
    console.log('运行在https端口:443')
})