node基于自签名证书搭建https服务

原文链接: https://www.cnblogs.com/yalong/p/18232314

描述

基于node.js 搭建一个https静态资源服务,由于只是本地用,所以使用自签名的ssl证书就行了
我用的mac 系统,系统自带有openssl的,其他系统如果没有请先安装

使用Openssl生成CA证书

  1. 生成 root 密钥:
openssl genrsa -out root.key 4096

  1. 生成 root 证书:
openssl req -new -x509 -days 1000 -key root.key -out root.crt

注意: 输入相关数据,不能全部都空着不写,可以随便写,我这里都写成 aa 也是可以的

  1. 验证 root 证书:
openssl x509 -text -in root.crt -noout

验证成功,如下图所示:

最终生成两个文件 root.key root.crt, 如下图所示:

使用Express搭建Https服务

主要代码如下:

const express = require('express')
const app = require("express")()
const fs = require("fs")
const path = require('path');

// 私钥跟证书
const httpsOption = {
  key: fs.readFileSync(path.join(__dirname, './ssl/root.key')),
  cert: fs.readFileSync(path.join(__dirname, './ssl/root.crt'))
}

// 创建https
const https = require("https").Server(httpsOption, app)
// 端口
const port = 443
// app.use(express.static(path.join(__dirname, 'public')));
// app.use('/static', express.static('public'))
app.use(express.static('public'));

// 定义根路由
app.get('/', (req, res) => {
  res.send("<h1>你好啊,https</h1>")
})

https.listen(port, () => {
  console.log(`服务启动成功!`)
  console.log(`https://localhost:${port}`)
})

https服务使用443端口就不用在url里写上端口号了,不过启动的时候,要加上sudo, 我demo里的启动方式就是 sudo npm run start

打开浏览器访问一个图片如下图所示

demo代码地址: https://github.com/YalongYan/node-express-https

posted @ 2024-06-06 09:52  进军的蜗牛  阅读(19)  评论(0编辑  收藏  举报